开发者

Release Quickie

开发者 https://www.devze.com 2022-12-28 01:42 出处:网络
How to succinctly handle this situation. I\'m not properly releasing contactDictionary in the if statement...

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].

0

精彩评论

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