Reputation: 7103
This is a general question about memory leaks. Let's say you have the following code:
NSObject *object = [[NSObject alloc] init];
NSArray *array = [[NSArray arrayWithObjects:object] retain];
[object release];
[array release];
Is that a memory leak? Like, would I have to enumerate through all the objects in the array and release them one by one before releasing the entire array? Or does NSArray's dealloc method release all of the objects within it as well as releasing the array itself?
Thanks for any help! Memory management can be quite tricky.
Upvotes: 0
Views: 155
Reputation: 48398
Here are some rules:
whenever you call alloc
, you must eventually call release
for every retain
, you should have a release
When you add an object to an array, it calls retain on that object. If you don't release your pointer to that object, it will be a leak. When you release the array, it will call release on all of the objects that it holds, since it called retain previously.
NSObject *object = [[NSObject alloc] init];
// object has retain count 1
NSArray *array = [[NSArray arrayWithObjects:object] retain];
// array is autoreleased but has a retain, so has retain count 1
// object now has retain count 2
[object release];
// object now has retain count 1
[array release];
// array is now set to autorelease,
// once that happens, array will be sent dealloc and object will be released
Hence no memory leaks.
Upvotes: 7