Reputation: 13998
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
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
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
Reputation: 141879
The retain count will be incremented in the first case. That's the correct approach.
Upvotes: 2