Search code examples
iphonecocoa-touchmemory-leaksxcode4instruments

Memory leak of an NSMutableArray using Instruments


According to the leak instrument in XCode it's saying this line is giving a memory leak (100%)?

self.unsentPatients = [[NSMutableArray alloc] initWithArray:[defaults arrayForKey:UNSENT]];

I'm correctly releasing etc. on dealloc (which is definitely being ran) so I don't understand where I am going wrong?

It's only a small leak and Analysis doesn't come up with anything, but nonetheless it's still a leak.

Kind regards,

Dominic


Solution

  • There are many things wring with this code.

    I'm assuming that the property is retaining the value, then you should not assign the value the way you are doing now, but more like:

    NSMutableArray *temp = [[NSMutableArray alloc] initWithArray:[defaults arrayForKey:UNSENT]];
    self.unsentPatients = temp;
    [temp release], temp = nil;
    

    or

    self.unsentPatients = [[[NSMutableArray alloc] initWithArray:[defaults arrayForKey:UNSENT]] autorelease];
    

    You should also avoid using the self. syntax in dealloc or init, which will call a mutator. In multithreaded environment this could give problems.

    So the correct dealloc would be:

    - (void) dealloc {
       [unsentPatients release], unsentPatients = nil;
       [super dealloc][;
    }