开发者

Delete object Coredata

开发者 https://www.devze.com 2023-03-12 09:55 出处:网络
I have a project that uses coredata and i am attmepting to delete from what i have stored. But i keep getting this error.

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];
        }
    }  


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.


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];
    }
}  
0

精彩评论

暂无评论...
验证码 换一张
取 消