views:

68

answers:

2

I have a NSMutableDictionary with the key being the first alphabet of the name of an object. The view is something like the 'Contacts' tab on iphone. Additionally user can select individual objects in the list.

In the code I find each selected object to process them further.

NSMutableArray *objectsToAdd = [[NSMutableArray alloc] init];
NSMutableArray *array      = nil;

for (NSString *key in self.nameIndex) {

    array = (NSMutableArray *)[searchedNameDictionary valueForKey:key];    
    for (Objects *eachObject in array) {
        if (eachObject.objectIsSelected){
            [objectsToAdd addObject:eachObject];
        }
    }           
}
[array release];

-(void)dealloc()
{
    [searchedNameDictionary release];
}

The app is crashing where I release searchedNameDictionary, with the message that the deallocated object is being referenced.

Now if in the code above, I remove [array release] the app works fine.

My question is does releasing 'array' is actually releasing the objects in searchedNameDictionary, which is what seems to be happening.

Would not releasing array cause memory leak?

+2  A: 

array = (NSMutableArray *)[searchedNameDictionary valueForKey:key];

This returns an autoreleased object, thus you don't need to release it.

There are some other...issues with your code too, but mostly style things. Get rid of the [array release] and you're good to go as far as that issue is concerned.

Joshua Weinberg
yes, removing the [array release] solves the problem as you said I was releasing an autoreleased object. From the apple documentation, I am struggling to find when a method returns an autoreleased object and when not. Is there anyway way of knowing what type(autoreleased or not) of object a method is returning.
prd
Yup, just follow the basic rules.http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html"You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” (for example, alloc, newObject, or mutableCopy), or if you send it a retain message. You are responsible for relinquishing ownership of objects you own using release or autorelease. Any other time you receive an object, you must not release it."This goes for everything.
Joshua Weinberg
+4  A: 

You shouldn't release returned object unless they come from an alloc or copy method.

Returned objects are autoreleased otherwise, if you want to keep it around your should retain it right after receiving it.

Ben S
Thanks, I should have applied the basic principle of memory management. Feel more confident with the code now. Thanks again for answering my question.
prd