开发者

Objective C, NSMutableDictionary reference count

    NSMutableDictionary *attrs = [nodeAttributes objectForKey:UUID];//nodeAttributes is NSMutalbleDictionary
    if (attrs == nil) {
         attrs = [[NSMutableDict开发者_开发百科ionary alloc] init];
         [nodeAttributes setObject:attrs forKey:UUID];
         [attrs release];
    }

I am not sure this code will works...Should I have something like this instead of this

    NSMutableDictionary *attrs = [nodeAttributes objectForKey:UUID];//nodeAttributes is NSMutalbleDictionary
    if (attrs == nil) {
         attrs = [[NSMutableDictionary alloc] init];
         [nodeAttributes setObject:[attrs retain] forKey:UUID];
         [attrs release];
    }

I am not sure if setObject method will increase the reference count...


NSMutableDictionary's setObject will retain the object (this is documented), so the first bit of code is correct and the second leaks. Style-wise, it may be more clear to a reader to do the following:

if (attrs == nil) {
     attrs = [NSMutableDictionary dictionary];
     [nodeAttributes setObject:attrs forKey:UUID];
}

Although memory-management-wise, your approach is probably better in that it avoids (implicitly) using autorelease.


The retain count will be incremented in the first case. That's the correct approach.


Objects are responsible for claiming ownership of the things they own. So yes, setObject:forKey: will retain. This is explained in detail (but still very briefly) in Apple's memory management guide.


setObject will send a retain message so you don't need to do that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜