Search code examples
iosautomatic-ref-countingnsthreadnsautoreleasepool

What might be happening if I release object, after releasing pool that object belongs to?


I am asking just logical question. Will object be released from memory if I release pool first and then release the object ? For example, here is my code snippet:


[self performSelectorInBackground:@selector(setImage) withObject:nil];

-(void)setImage
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];

    NSString *strUrl = @"--some URL--";

    NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:strUrl]];
    UIImage *myimage = [[UIImage alloc] initWithData:imageData];

    [pool release];
    [imageData release];
}

Assume that the code snippet executes under non-ARC environment.


Solution

  • This will be fine as you never added the imageData object to the autorelease pool, so the pool won't release it. If you had added the imageData object to the autorelease pool like this:

    [[[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:strUrl]] autorelease];
    

    The extra release would be an overrelease and your app may crash. It looks like you've leaked myImage as this is never released.