Search code examples
objective-cmemory-leaksreleasensdictionaryrelease-management

Objective C: Releasing a list, will it cause potential leaks?


Tried finding the answer online, but couldn't. So i'm wondering if anyone else knows and why?

Say I have an NSDictionary, or NSArray, that stores objects inside of them. If I release the NSDictionary, is there a potential leak because I didn't release the objects inside of the NSDictionary list?

For example:

NSDictionary *dict = [NSDictionary alloc] init];
// Create a bunch of objects, NSStrings, etc.
// Store it into dict.
[dict release];

Will that also release everything inside of the dict? (objects, nsstrings, etc).
Thanks in advance people!


Solution

  • All items in an NSDictionary or NSArray are automatically retained when they're added and released when removed, or when the list is destroyed.

    For example:

    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    
    MyObject *obj = [[MyObject alloc] init];
    [dict setObject:obj forKey:@"foo"];  // the dictionary retains "obj"
    [obj release];  // this matches the "alloc/init"
                    // but "obj" still is retained by the dictionary
    
    [dict release];  // now "obj" gets released