views:

287

answers:

3

Hello,

I hava a UINavigationController. The first level is a UITableViewController, the second level just shows details on one of the items of the table view.

In this detail view, I can delete the item. It deletes the underlying managed object.

When I pop back to the view, I have a crash. I understand why, it's because I didn't update the cached array that contains the data.

I looked at several tutorials and I don't exactly understand how am I supposed to handle deletion. Maybe I don't understand exactly where I should fetch the objects in the model. Should I do a query for every cellForRowAtIndexPath and take the item in the result at position indexPath.row? It doesn't look efficient. Should I check for changes somewhere and recache the whole query in an array. I would think CoreData would provide something more natural but I couldn't find it so far.

Thanks in advance.

+1  A: 

It seems somewhat non-standard deleting an item in the parent controller from your detail controller, but perhaps it makes sense in your case. I presume you know that you can directly delete items in the tableview. There are many example code projects from Apple which along with the docs should give you an idea how to do that.

To answer your question, you could create a property/variable in your detail controller's class which holds a reference to the tableview controller then send a message to that controller to handle the delete. Creating a protocol for this would be good style but not necessary. When the tableview class receives the delete item message, it updates the array, and when that view is redisplayed you should call reloadData on the tableview. This is the standard paradigm: make changes to your underlying data model and tell the tablview to reload.

wkw
It often happens to be able to delete the item in the child view. For instance in the mail app you can delete both in the tableview but also in the detail view.I was wondering about reloadData but what if my table view contained huge amounts of data (this is not the case but I would like to know the best practice): wouldn't it be bad to reload the whole model when just one object disappeared?
Kamchatka
You can also look at UITableView's -deleteRowsAtIndexPaths:withRowAnimation:
Hwee-Boon Yar
+1  A: 

It is fairly simple. In the child view you should (really, really should) have a reference to the NSManagedObject you are working with. When you want to delete it then you just:

NSManagedObjectContext *moc = [[self myObject] managedObjectContext];
[moc deleteObject:[self myObject]];
NSError *error = nil;
if (![moc save:&error]) {
  NSLog(@"Save failed: %@\n%@", [error localizedDescription], [error userInfo]);
}

This will delete the object. The parent, since it is using a NSFetchedResultsController (which you should also REALLY be doing) will take care of itself.

Marcus S. Zarra
Thanks, this is really clean, I did that and it solved my problem.
Kamchatka
+1  A: 
DenTheMan