Why do I get: Illegal attempt to establish a relationship ... between objects in different contexts
I only have one managed object context.
I have modified the managed object store though.
There are certain fields that I would like to add to every managed object. It would take far too much time to add them all one by one to every object in my system, so I decided to add them programmatically to the managed object model. In the application delegate, I first do:
managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];
Then I iterate through all the entities in the model and modify them and set the new property array for each one:
for (NSEntityDescription *entity in entities) {
NSAttributeDescription *idAttribute = [[NSAttributeDescription alloc] init];
[idAttribute setName:@"id"];
[idAttribute setAttributeType:NSStringAttributeType];
[idAttribute setOptional:NO];
[idAttribute setIndexed:YES];
and so on.
It seems to mostly work fine. I run into problems when I am trying to add an object to a new one-to-one relationship I created. I create the objects from the same managed object context:
self.action = [NSEntityDescription insertNewObjectForEntityForName:@"MobileObjectAction" inManagedObjectContext:managedObjectContext];
self.user = [NSEntityDescription insertNewObjectForEntityForName:@"MobileUser" inManagedObjectContext:managedObjectContext];
When I get to
[user setAction:action];
I get: Terminating app due开发者_StackOverflow中文版 to uncaught exception 'NSInvalidArgumentException', reason: 'Illegal attempt to establish a relationship 'action' between objects in different contexts ...
What am I doing wrong?
Put a breakpoint in your code just before the two Entities are related. Make sure they are both instances of NSManagedObject
.
If they are, make sure both of them have their NSManagedObjectContext
set and it is set to the same pointer.
Obviously, make sure they are both valid objects.
Most likely one of the above tests will prove false.
I have the same problem and solve it:
- one context (no splitting/merging).
- set property -> and get "Illegal attempt to establish a relationship between objects..."
so - W ha T 's wrong and what I mast F ound and correct?
answer is simply: before
[meeting setCreator: [self currentUser]];
after
[meeting setCreator: _currentUser];
and for info
*.h
@interface{
Person* _currentUser;
}
@property (readonly, retain) NSManagedObjectContext *managedObjectContext;
- (Person*)currentUser;
*.m
@synthesize managedObjectContext = _managedObjectContext;
- (Person*)currentUser{
return _currentUser;
}
- (NSManagedObjectContext *) managedObjectContext {
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator: coordinator];
}
return _managedObjectContext;
}
精彩评论