Illegal attempt to establish a relationship 'xyz' between objects in different contexts

后端 未结 6 1174
傲寒
傲寒 2020-12-23 13:44

I am using Apple\'s CoreDataBooks sample application as a basis for pulling data into a secondary managed object context in the background, and then merging tha

6条回答
  •  别那么骄傲
    2020-12-23 14:12

    You can't have relationships between objects in different managed object contexts. So one way of getting around that is to bring the object into the managed object context.

    For example:

    NSManagedObject *book = // get a book in one MOC
    NSManagedObject *owner = // get an owner in a different MOC
    [[owner mutableSetValueForKey:@"books"] addObject:[owner.managedObjectContext objectWithID:[book objectID]]];
    

    So what you're doing is actually fetching the Book into the same managed object context with owner. Keep in mind, though, that this is only possible if book has already been saved. The managed object context is going to look for the object in the persistent store, so it has to be saved first.

提交回复
热议问题