releasing Objects of an NSMutableArray

Discussion in 'Mac Programming' started by Tex-Twil, Dec 18, 2009.

  1. Tex-Twil macrumors 68020

    Tex-Twil

    Joined:
    May 28, 2008
    Location:
    Europe
    #1
    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
     
  2. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    The array will be retaining the object: you should be adding released or autoreleased objects to it.
     
  3. Tex-Twil thread starter macrumors 68020

    Tex-Twil

    Joined:
    May 28, 2008
    Location:
    Europe
    #3
    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
     
  4. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #4
    Sure, but you can do:
    Code:
    id myObject = [[Object alloc] init];
    [myArray addObject:myObject];
    [myObject release];
    
     
  5. Tex-Twil thread starter macrumors 68020

    Tex-Twil

    Joined:
    May 28, 2008
    Location:
    Europe
    #5
    ok i got it ;)
     

Share This Page