James Dunay
James Dunay

Reputation: 2724

Delete object Coredata

I have a project that uses coredata and i am attmepting to delete from what i have stored. But i keep getting this error.

An NSManagedObjectContext cannot delete objects in other contexts.

I looked at what apple had to say and from what i can tell i have it correct, but something is still off. Any suggestions? Thx!

for (UserNumber *info in pinNumberArray) {

        NSSet *time = [[NSSet alloc] initWithSet:info.Times];

        for (ErgTimes *ergTimes in time){

            NSMutableArray *temp = [[NSMutableArray alloc] initWithObjects:ergTimes.Twok, nil];
            NSManagedObject *eventToDelete = [temp objectAtIndex:0];
            [managedObjectContext deleteObject:eventToDelete];
        }
    }  

Upvotes: 3

Views: 10666

Answers (2)

Massimo Cafaro
Massimo Cafaro

Reputation: 25429

You must use the same NSManagedObjectContext you used to fetch the objects to delete them. Easiest solution: use the managedObjectContext associated to each object to delete it. Like this:

for (UserNumber *info in pinNumberArray) {

    NSSet *time = [[NSSet alloc] initWithSet:info.Times];

    for (ErgTimes *ergTimes in time){

        NSMutableArray *temp = [[NSMutableArray alloc] initWithObjects:ergTimes.Twok, nil];
        NSManagedObject *eventToDelete = [temp objectAtIndex:0];
        [eventToDelete.managedObjectContext deleteObject:eventToDelete];
    }
}  

Upvotes: 0

Daniel Thorpe
Daniel Thorpe

Reputation: 3931

Well, it's possibly that you've got your objects, context and threads mixed up. NSManagedObjectContext isn't thread safe. To delete an object from a context, you need to have fetched the object "into" the context first, and I guess your managed object was fetched by a different MOC. Without seeing more code I can't tell.

However, there is a relatively easy fix. In your for loop, do this instead

for (ErgTimes *ergTimes in time){
    NSMutableArray *temp = [[NSMutableArray alloc] initWithObjects:ergTimes.Twok, nil];
    NSManagedObject *eventToDelete = [managedObjectContext objectWithID:[[temp objectAtIndex:0] objectID]];
    [managedObjectContext deleteObject:eventToDelete];
}

What this does is get the object in the MOC your currently using using its objectID which is thread-safe.

Upvotes: 11

Related Questions