views:

130

answers:

2

I am working with an app similar to apple's core data recipes sample code. I want to be able to delete the entry from the detail view, much like apple's contacts app.

The code below is deleting the 1st entry and not the selected entry. Not sure what I am doing wrong.

NSIndexPath *indexPath = [myTableView indexPathForSelectedRow];
NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
[context deleteObject:[fetchedResultsController objectAtIndexPath:indexPath]];
[myTableView reloadData];
A: 

The most likely problem is that indexPathForSelectedRow: is not returning the indexpath you think it is. Alternatively, if you section name key path is not setup correctly when you configured the fetched results controller, then you can get odd returns because it looses track of which rows go with which section.

TechZen
I might be going about this all wrong. I want to give the user the ability to cancel an entry they started. Or when they have finished creating an entry, to be able to delete it. I have a cancel button in the AddViewController that is a delegate to the RootController that triggers the above the code.How do I get the IndexPath to know the entry that the user is currently working with?
Sam
Don't bother with the indexPath. You should have a reference to the managedObject and can delete it from the managedObjectContext. The fetchedResultsController should handle the delete for you and update the table automatically.
MrHen
Yes, I agree. If you have the object in hand, such as in a detail view, then you have don't have to use its index in the fetched results controller or anywhere else. Each managed object is tied to its context. Just tell the context to delete it and its gone. The fetched results controller will be observing the context and will automatically update the table for you.
TechZen
Would it look something like?-(void)deleteEntry { NSManagedObjectContext *context; [context deleteObject:entry];}
Sam
A: 

Thanks for the help. This is the code that did the trick

NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];

[context deleteObject:entry]; [myTableView reloadData];

Sam