Release Quickie
How to succinctly handle this situation. I'm not properly releasing contactDictionary
in the if
statement...
NSNumber *pIDAsNumber;
... 开发者_C百科
NSMutableDictionary *contactDictionary = [NSMutableDictionary dictionaryWithDictionary:[defaults dictionaryForKey:kContactDictionary]];
if (!contactDictionary) {
contactDictionary = [[NSMutableDictionary alloc] initWithCapacity:1];
}
[contactDictionary setObject:pIDAsNumber forKey:[myClass.personIDAsNumber stringValue]];
[defaults setObject:contactDictionary forKey:kContactDictionary];
Normally, use [NSMutableDictionary dictionaryWithCapacity:1]
instead of alloc/init. That will give you an autoreleased dictionary that will, from a memory management perspective, behave identically to the one above. However...
In this specific case, your if clause will never be true (unless you run out of memory, in which case you have bigger problems). -dictionaryWithDictionary:
returns an empty dictionary rather than nil if it is passed nil. So, even if -dictionaryForKey:
returns nil, -dictionaryWithDictionary:
will still create an empty mutable dictionary for you to add to.
You can drop the if
statement entirely, because -[NSMutableDictionary dictionaryWithDictionary:]
always returns a dictionary.
Also, don't use [NSMutableDictionary dictionaryWithCapacity:1]
to get an empty, autoreleased mutable dictionary. Just use [NSMutableDictionary dictionary]
.
精彩评论