From Notification Watcher source.
- (void)selectNotification:(NSNotification*)aNotification {
id sender = [aNotification object];
[selectedDistNotification release];
selectedDistNotification = nil;
[selectedWSNotification release];
selectedWSNotification = nil;
NSNotification **targetVar;
NSArray **targetList;
if (sender == distNotificationList) {
targetVar = &selectedDistNotification;
targetList = &distNotifications;
} else {
targetVar = &selectedWSNotification;
targetList = &wsNotifications;
}
if ([sender selectedRow] != -1) {
[*targetVar autorelease];
*targetVar = [[*targetList objectAtIndex:[sender selectedRow]] retain];
}
if (*targetVar == nil) {
[objectText setStringValue:@""];
} else {
id obj = [*targetVar object];
NSMutableAttributedString *objStr = nil;
if (obj == nil) {
NSFont *aFont = [objectText font];
NSDictionary *attrDict = italicAttributesForFont(aFont);
objStr = [[NSMutableAttributedString alloc] initWithString:@"(null)"
attributes:attrDict];
} else {
/* Line 1 */ objStr = [[NSMutableAttributedString alloc] initWithString:
[NSString stringWithFormat:@" (%@)", [obj className]]];
[objStr addAttributes:italicAttributesForFont([objectText font])
range:NSMakeRange(1,[[obj className] length]+2)];
if ([obj isKindOfClass:[NSString class]]) {
[objStr replaceCharactersInRange:NSMakeRange(0,0) withString:obj];
} else if ([obj respondsToSelector:@selector(stringValue)]) {
[objStr replaceCharactersInRange:NSMakeRange(0,0)
withString:[obj performSelector:@selector(stringValue)]];
} else {
// Remove the space since we have no value to display
开发者_如何学C [objStr replaceCharactersInRange:NSMakeRange(0,1) withString:@""];
}
}
[objectText setObjectValue:objStr];
/* LINE 2 */ [objStr release];
}
[userInfoList reloadData];
}
Over at //LINE 2 objStr is being released. Is this because we are assigning it with alloc in //LINE 1?
Also, why is //LINE 1 not:
objStr = [NSMutableAttributedString* initWithString:@"(null)"
attributes:attrDict]
If I create a new string like
(NSString*) str = [NSString initWithString:@"test"];
...
str = @"another string";
Would I have to release str, or is this wrong and if I do that I have to use [[NSString alloc] initWithString:@"test"]? Why isn't the pointer symbol used as in [[NSString* alloc] ...?
Thanks
It is being released because it was allocated. The alloc
has the effect of a retain
and must be balanced by a release
(or autorelease
). Pretty much any method that begins with init
results in an object that needs to be released. It is all about balancing the retains with the releases.
精彩评论