codereviewanskquestions
codereviewanskquestions

Reputation: 13998

Objective C, NSMutableDictionary reference count

    NSMutableDictionary *attrs = [nodeAttributes objectForKey:UUID];//nodeAttributes is NSMutalbleDictionary
    if (attrs == nil) {
         attrs = [[NSMutableDictionary 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...

Upvotes: 2

Views: 2977

Answers (4)

Anomie
Anomie

Reputation: 94794

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.

Upvotes: 4

Chuck
Chuck

Reputation: 237060

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.

Upvotes: 2

Nevin
Nevin

Reputation: 7809

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

Upvotes: 0

Anurag
Anurag

Reputation: 141879

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

Upvotes: 2

Related Questions