views:

23

answers:

1

Hi everybody, I need to understand something about NSManagedObjectContext update. I have a UISplitView with a UITableViewController on the RootView and a UIViewController on the Detail View. When I tap in a row with data, I load some data into labels and a UITextView where I can update that field:

- (void)textViewDidEndEditing:(UITextView *)textView {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
[[listOfAdventures objectAtIndex:indexPath.row] setAdventureDescription:textView.text];
}

Ok. This works correctly, the description is updated. Also, someone might wants to delete a row:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

if (editingStyle == UITableViewCellEditingStyleDelete) {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"playerPlaysAdventure.adventureName==%@",[[listOfAdventures objectAtIndex:indexPath.row] adventureName]];
    NSArray *results = [[AdventureFetcher sharedInstance] fetchManagedObjectsForEntity:@"Player" withPredicate:predicate withDescriptor:@"playerName"];

    [moc deleteObject:[listOfAdventures objectAtIndex:indexPath.row]];
    for ( Player *player in results ) {
        [moc deleteObject:player];
    }
    [listOfAdventures removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    [self clearDetailViewContent];
    NSError *error = nil;
    if ( ![moc save:&error] ) {
        NSLog( @"Errore nella cancellazione del contesto!" );
        abort();
    }
}   
else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}   
}

So here's my problem: if I comment the rows about the saving of my MOC, the adventure is only momentarily deleted. If you quit the app and the reopen it, the object is still there. This doesn't happen with the update of a field. I'd like to know why and if I should save moc also in textViewDidFinishEditing method. Thank you in advance.

+1  A: 

It's the difference between changing an attribute of an object and adding or removing an entire object in the object graph.

In the first block, you change an attribute of an existing object which saves automatically unless you run an undo. This is because the object already exist in the object graph and no other objects have to be altered to make the change.

In the second block, you are removing an entire object and potentially altering the object graph itself by changing the relationships between objects. That change will not be committed until an implicit save because potentially it can trigger a cascade of changes throughout a large number of objects.

TechZen