Search code examples
objective-coopnsmutabledictionaryownership

NSMutableDictionary not calling 'release' upon removing object


From what I have understood, NSMutableDictionary releases all objects when released itself. I wrote a test for this:

#import <Foundation/Foundation.h>

int main(int argc, char *argv[]) 
{
    @autoreleasepool 
    {
        NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];

        NSObject *object = [[NSObject alloc] init];
        [dictionary setObject:object forKey:@"key"];
        [dictionary release];

        NSLog(@"%@", object);
    }
}

However, the object still exists, and has not been deallocated:

2014-02-15 09:34:31.883 Untitled[15548:707] <NSObject: 0x7fa0b9c09c60>

Why is this so?


Solution

  • You've done an alloc & init on your "object". That makes the retain count 1.

    When you add it to your dictionary, that makes the retain count 2.

    When you release the dictionary, the retain count of the object is decremented to 1.

    Which is why you can print out the "contents" of it, since "object" has a retain count of 1 and has not been truly released yet.