簡體   English   中英

使Notification Watcher源Objective-c變得有意義

[英]Make sense of Notification Watcher source objective-c

從Notification Watcher源。

- (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中用alloc分配了它嗎?

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

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

如果我創建一個新的字符串像

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

我必須釋放str還是這是錯誤的,如果這樣做,我必須使用[[NSString alloc] initWithString:@“ test”]? 為什么不使用[[NSString * alloc] ...中的指針符號?

謝謝

由於已分配,因此正在釋放它。 alloc具有retain的作用,並且必須由release (或autorelease )平衡。 幾乎所有以init開頭的方法都會導致需要釋放一個對象。 這是關於平衡保留和發布之間的全部。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM