views:

250

answers:

2

Hello. I am working on an iPhone app that will construct, at run-time, an NSMutableDictionary for which the values (of the key-value pairs) will be NSMutableArrays. Being somewhat new to the Objective-C, I am concerned that the following will cause a memory leak:

- (void) addNewSupplierPhoto:(UIImage*)image toSupplierID:(NSInteger*) supplierID{
NSMutableArray* supplierPhotoArray = [supplierPhotos objectForKey:supplierID];
if(supplierPhotoArray == nil)
{
    supplierPhotoArray = [[NSMutableArray alloc] init];
    [supplierPhotos setObject:supplierPhotoArray forKey:supplierID];
    [supplierPhotoArray release];
}
}

supplierPhotos is an NSMutableDictionary, which is a member variable of the containing class.

As you can see, when I am accepting a new UIImage* to put into the structure, I first check to see if the object at the key-value pair corresponding to the second argument (supplierID) is nil. If it is nil, I alloc a new NSMutableArray and set it as the object for that key, then release it. Assuming I dealloc the NSMutableDictionary in the dealloc of the class containing this method, will the references be released? Before dealloc-ing the NSMutableDictionary, do I need to run through it and dealloc the individual NSMutableArrays contained within?

Thanks,

Ben B.

A: 

this memory management looks correct to me. You release the one copy you've alloc'd, and the array holds another reference once you add to it, so the net count is 1 which is correct.

darren
Thanks darren. Do I need to walk the NSMutableDictionary and release each NSMutableArray within before I release the NSMutableDictionary?
Ben Birney
I would look at the NSDictionary ref docs, BUT i'm almost certain that when an NSArray or NSDictionary is released, it sends release messages to each of the items it is holding.
darren
the "build and analyze" menu item in xCode does a pretty decent job of highlighting potential memory leaks when in doubt.
wkw
+2  A: 

when you add objects into an container like dictionary or array, retain will be invoked automatically, and when you release the container as your question it's dictionary, it will call 'release' of every object to dealloc the object's memory.

Ricky