Memory leaks with ARC


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.

How to find memory leaks with Instruments

Leave a comment

I had a memory leak in my app and after hooking up my iPhone and running ‘Profile without building’ I got a Instruments Leaks screen pop up that looked like this:

Not knowing how to find the offending line of code I found clicking on the calltree stack and selecting ‘Hide System Libraries’ and ‘Show Obj-C Only’ options helped me see what was wrong.

And here was the offending class.

And double clicking this line brought up the actual line of code.


%d bloggers like this: