iOS Developer
iOS Developer

Reputation: 1723

app crashes when deleting an object from core data in iphone

I have populated a table view with some data from server and saved it to the core data.Now i have to delete the object from the core data when the user clicks on the delete option in the table view. What i have tried is this:`

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath   
{
    NSError *error; 
    [[Server serverInfo].context deleteObject:[self.couponList objectAtIndex:indexPath.row]];
    if(![ [Server serverInfo].context  save:&error]) {
        // Handle error
        NSLog(@"Unresolved error series %@, %@", error, [error userInfo]);
    }
    [self.couponList removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                     withRowAnimation:UITableViewRowAnimationFade];
    if ([self.couponList count]==0) {
        [self.table setEditing:NO animated:YES];
        [self.editBt setStyle:UIBarButtonItemStyleBordered];
    }

}

` But it gives an exception and crashes.This is i am getting in the log :"Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'An NSManagedObjectContext cannot delete objects in other contexts".'Can anyone solve this?Thanks in advance

Upvotes: 1

Views: 1417

Answers (3)

faterpig
faterpig

Reputation: 344

Agree with Mundi.

On top of that, if you require many instances of the managedObjectContext, do not create that many but rather use the lock and unlock functions of the NSManagedObjectContext to enable multi-threading without issues on faults and invalidation of the objects.

EDIT

Maybe you can try creating just one NSManagedObjectContext in the AppDelegate and call the same managedObjectContext from the controllers where you need to use them. This, and together with the lock and unlock methods solved my issue with the multi-threading and invalidation of the objects.

Hope this helps.

Upvotes: 0

Mundi
Mundi

Reputation: 80265

Apparently you are using more than one managed object context. This is indicated by your error message. Make sure that you are using only one managed object context, i.e. that there are no background tasks that use a different one.

You are keeping the data for your table view in a separate array. This might be another problem. The proper way to deal with core data and table views is to employ the NSFetchedResultsController.

Upvotes: 1

Saad
Saad

Reputation: 8947

you have to make some manageobject context, a fetch request and then remove object using some predicate.

Upvotes: 1

Related Questions