views:

100

answers:

1

The following code deletes a core data object if the user did not end up modifying the new entry (this happens on an insert operation). The root view controller created the entity and passed a reference to my view. It works fine if the user hits a "done" button on my view, but if instead they navigate backwards using the "back" button on the nav bar, the root view it returns to just hangs forever.

Am I doing something obviously wrong? I have considered waiting to create the entity until the user is finished with the view, but in the future this view will also handle editing existing entities, so my current method of passing an existing entity to this view is preferred.

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    // If the baby has no name, delete the Baby object that the root view
    // already created. Otherwise save it.
    NSManagedObjectContext *context = self.baby.managedObjectContext;

    if ( [self.babyNameField.text length] == 0 )
        [context deleteObject:baby];

    // Save
    NSError *error = nil;
    if (![context save:&error]) {
        // unresolved jmu - handle error
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);     
    }

}
A: 

This is a common approach and this code looks fine.

Have you set a breakpoint on it and walked through to make sure? You need to debug and track down where the code is hanging.

gerry3
Thanks for letting me know this is a standard way to accomplish this. I did step through it and the method completes with no errors. If I break the debugger after it hangs there really isn't anything interesting on the stack (at least not to an iPhone newbie):mach_msg_trap -> mach_msg -> CFRunLoopRunSpecific -> ...
Jeremy Mullin
Ahh. Newbie. I didn't have the console window open. It wasn't hung, it had stopped on an exception "CoreData could not fulfill a fault". I must have to do something else so the view I'm returning to doesn't have a reference to the entity I deleted...
Jeremy Mullin
I was able to fix this, although it was kind of a work-around. The code started from a tutorial where the entity was saved right after it was created and before the new view was created. I removed that code since I now save it when the new view closes. Since I'm now no longer saving in the root view, whatever is holding a reference to that new entity doesn't get it, and doesn't cause the problem anymore. I'd still like to know what the heck it was. I'm guessing it is the table view in the root view, but I couldn't pin it down for sure.
Jeremy Mullin