Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Tex-Twil

macrumors 68030
Original poster
May 28, 2008
2,501
15
Berlin
Hello,
I would like to know what is the correct way of releasing Objects that are referenced in a NSMutableArray. Here is my simple code but I get warnings about memory leaks

Code:
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
							 
	NSMutableArray *array = [[NSMutableArray alloc ] initWithCapacity:3];
	
	[array addObject:[[PolygonShape alloc] init]];
	[array addObject:[[PolygonShape alloc] initWithNumberOfSides:3]];
	
	
	for(PolygonShape *curr in array) {
		NSLog([curr description]);
	}


	for(PolygonShape *curr in array) {
		[curr release];
	}
	 
	[array release];
    [pool drain];
    return 0;
}

I implemented the dealloc of my PolygonShape objects (to add a simple log) and they are not called by the 2nd loop. It looks like they are called only by [array dealloc]

Strange is that if I comment the dealloc loop, the [PolygonShape dealloc] method is not called at all.

What am I doing wrong here ?

Thanks,
Tex
 
The array will be retaining the object: you should be adding released or autoreleased objects to it.

Oh I see now. My 1st release had no effect cos the array retained the object hence the retain count wasnt 0.

Code:
	[array addObject:[[[PolygonShape alloc] init] autorelease]];
This works better.

What do you mean by "released objects" ? If I released my objects before adding them to the array, they would have been deallocated.

Thanks for your quick answer.

Tex
 
What do you mean by "released objects" ? If I released my objects before adding them to the array, they would have been deallocated.

Sure, but you can do:
Code:
id myObject = [[Object alloc] init];
[myArray addObject:myObject];
[myObject release];
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.