Feby Elizabeth
Feby Elizabeth

Reputation: 11

How to delete a row from core data and table view

I am getting an error “An NSManagedObjectContext cannot delete objects in other contexts” while trying to delete an object from the core data. i am using the below code in the load after the normal core data fetch

    NSFetchedResultsController  *controller = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:appDelegate.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
    controller.delegate=self;
    BOOL success = [controller performFetch:&error];


    -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
     {
     NSManagedObject *managedObject = [controller objectAtIndexPath:indexPath];
     //(Alert view)
     } 

In the alert view clickedButtonAtIndex function , i am trying to delete that particular managed object from the appDelegate.managedObjectContext , but an error “An NSManagedObjectContext cannot delete objects in other contexts” occurs in the line

    [appDelegate.managedObjectContext deleteObject:managedObject];   

i tried with other managed object context ,

    NSManagedObjectContext *context= [controller managedObjectContext];

but getting the same error. Can anyone please tell why this error occurs and a solution to delete a particular row from the table view and the core data?

Upvotes: 0

Views: 128

Answers (2)

wattson12
wattson12

Reputation: 11174

You are using a different context to the one the object is from (exactly what the error says), change the delete line to

[managedObject.managedObjectContext deleteObject:managedObject];

Upvotes: 1

Ravi Sisodia
Ravi Sisodia

Reputation: 776

Use the same NSManagedContext to delete that's used to fetched the objects, and in the same thread also.

Upvotes: 0

Related Questions