When to release an object added to an NSMutableDictionary
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.
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.
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.
精彩评论