ARC (Automatic Reference Counting) is great, but it Cocoa doesn’t set it up for us on background threads, so we can still get memory leaks from application code that calls non-ARC Apple frameworks.

To get the benefits of ARC on any background (or asynchronous) thread calls, wrap the code in an @autorelease pool:

- (void)doSomething {
    [self performSelectorInBackground:@selector(backgroundSomething)];
}

- (void)backgroundSomething {
    @autoreleasepool {
        NSLog(@"Here I am in the background, doing something.");
        myArray = [[NSMutableArray alloc] init];
        // etc.
    }
}

This will autorelease the objects you create here just like they would on the mainthread.

Thanks Stackoverflow for pointing this out.

Advertisements