理解Notification Watcher源目标-c

时间:2010-04-02 20:40:14

标签: objective-c memory-management

来自通知观察者来源。

- (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
            [objStr replaceCharactersInRange:NSMakeRange(0,1) withString:@""];
        }
    }
    [objectText setObjectValue:objStr];
/* LINE 2 */    [objStr release];
}
[userInfoList reloadData];

}

在// LINE 2上,objStr正在发布。这是因为我们在// LINE 1中分配了它吗?

另外,为什么// LINE 1不是:

objStr = [NSMutableAttributedString* initWithString:@"(null)"
                                                    attributes:attrDict]

如果我创建一个新的字符串,如

(NSString*) str = [NSString initWithString:@"test"];
...
str = @"another string";

我是否必须释放str,或者这是错误的,如果我这样做,我必须使用[[NSString alloc] initWithString:@“test”]? 为什么指针符号不能用作[[NSString * alloc] ...?

由于

1 个答案:

答案 0 :(得分:0)

它正在被释放,因为它被分配了。 alloc具有retain的效果,必须由release(或autorelease)进行平衡。几乎任何以init开头的方法都会导致需要释放的对象。这一切都是为了平衡保留与发布。