Saturday, August 28, 2010

The autorelease lightbulb

In my use of some CoreData objects I ran into a situation where I was getting an EXC_BAD_ACCESS crash. This error essentially means that you are accessing an object that has already been released. I tried a couple of different ways to find the error and finally pinned the code down to this:

Photo *photo = [NSEntityDescription insertNewObjectForEntityForName:@"Photo" inManagedObjectContext:[myFF managedObjectContext]];

photo.name = [key objectForKey:@"name"];

photo.path = [key objectForKey:@"path"];

photo.photoOwner = person;

[[myFF managedObjectContext] save:&error];


[photo release];


The problem lies in the reference counting on the photo object. It turns out that insertNewObjectForEntityForName will return an autoreleased object per the documentation.

Return Value

A new, autoreleased, fully configured instance of the class for the entity named entityName.


Because I am releasing the photo object also it causes the aforementioned error.

Lesson learned: read the documentation!


No comments:

Post a Comment