Question

I have been battling this for a long time now. My understanding of Autorelease is that when it doesnt need it any longer it will release it.

I was getting one of those evil EXC_BAD_ACCESS without any details. It would just crash on:

 int main(int argc, char *argv[])
 {
     @autoreleasepool {
         return UIApplicationMain(argc, argv, nil, NSStringFromClass([Logix_AppDelegate      class]));
     }
 }

With Zombies enabled I found that I was writing to CoreData in a loop here is my initialization of the NSManagedObjectContext

  NSManagedObjectContext *context = [[(MyAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext] autorelease];

Any thoughts here.... there is a lot of code, so I didnt want to paste volumes of stuff here.

Was it helpful?

Solution

autorelease adds an object to the current autorelease pool. That object will receive a release message (and potentially be deallocated) when the current autorelease pool is destroyed.

Sending autorelease to an object makes sense only if you own that object. In your case, the managedObjectContext method has not "new", "alloc" or "copy" in its name, so you don't own the returned object and must not call autorelease on it.

So you should replace that line by

NSManagedObjectContext *context = [(MyAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];

See also Memory Management Policy in the "Advanced Memory Management Programming Guide":

You own any object you create
You create an object using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy” (for example, alloc, newObject, or mutableCopy). ...

When you no longer need it, you must relinquish ownership of an object you own
You relinquish ownership of an object by sending it a release message or an autorelease message. ...

You must not relinquish ownership of an object you do not own

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top