Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
        }
    }  
like image 893
James Dunay Avatar asked Dec 09 '25 02:12

James Dunay


1 Answers

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.

like image 101
Daniel Thorpe Avatar answered Dec 10 '25 15:12

Daniel Thorpe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!