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.
Apr 09, 2012 @ 14:13:27
That’s why you should be using NSOperation instead of naked NSThread’s.
Apr 10, 2012 @ 03:31:36
Ah thank you. I didn’t realize NSOperation wrapped calls in GCD.
Apr 27, 2012 @ 11:25:43
I still get memory leaks even with NSOperation. Here is how I call it
NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(workerThreadFetchData)
object:nil];
[queue addOperation:operation];
-(void)workerThreadFetchData{
//fetches data from rest services and parses data with SBJson
}
All of the memory leaks happen in SBJson libraries. Any ideas???? Shouldn’t the operation take care of the memory management
Apr 27, 2012 @ 14:25:07
NSOperation may be GCD safe, but it can’t control what’s going on in 3rd party non-Arc libraries.
If you are getting memory leaks using SBJson, there may be something in their that isn’t being let go (causing the leak).
Apr 27, 2012 @ 14:29:17
Yeah good call JR, I dumped SBJson for JSON kit and its awesome!
By the way if you want to use a non arc library in an arc project, look at the last answer here where he talks about compiler flags: http://stackoverflow.com/questions/6448874/disable-automatic-reference-counting-for-some-files
Great blog dude!
Apr 29, 2012 @ 15:56:09
Thank you. I also wrote up a similar post on ARC non-ARC builds here:
https://agilewarrior.wordpress.com/2012/04/23/how-to-include-non-arc-file-in-your-arc-project/
Cheers