views:

159

answers:

2

Hi all,

I'm having a problem with a Core Data project on the iPhone. The scenario occurs when a user starts to add an object, then cancels during the process.

If the user hits cancel and returns to the list of objects, a dummy object is listed there, representing the one they were in the middle of creating. This is never saved to the database - saves occur as expected when the user hits the save button.

When the view controller where the user adds data is loaded, I create a new Thing object - this is the Core Data entity that I am adding:

myThing = [NSEntityDescription insertNewObjectForEntityForName:@"myThing" inManagedObjectContext:managedObjectContext];

I tried to delete this in my cancel method as follows:

[managedObjectContext deleteObject:myThing];

When I do this, I get a EXC_BAD_ACCESS when I hit cancel. Stepping through the code in the debugger, it gets through the cancel method fine, but this is being generated in the root view controller where I list my objects and also where I was before I tried to create this object.

All I'm trying to achieve is allowing the user to add a new object, but cancel part-way through.

Any ideas what is causing this error? I am unable to generate a stack trace from this unfortunately :(

+1  A: 

Your approach to the object cancel is typical and appropriate.

Memory errors are common and can be tough to debug. Have you run the static analyzer? You may want to set your "myThing" reference to nil after deleting it from the context.

Do you know for sure that it is the cancel workflow that is leading to the memory error?

gerry3
I'm pretty sure it's the cancel. If I do a save, everything works right. If I remove the [... deleteObject:myThing]; from the cancel method, then the crash no longer occurs.Would it make any sense to use a different managed context in this controller instead of the one being passed in by the RootController ?
Anonymouslemming
Hmmm - Ignore my previous comment. Setting myThing = nil in the cancel method appears to resolve this problem.I was doing [myThing release] in the dealloc method, but just setting this to nil has made the problem go away.Thanks!
Anonymouslemming
A: 

You can also turn on NSZombie and find out what released object is being accessed. That will help you quickly track this issue down. Google NSZombie for a few examples of how to use it.

Marcus S. Zarra