views:

45

answers:

1

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 to uncaught exception 'NSInvalidArgumentException', reason: 'Illegal attempt to establish a relationship 'action' between objects in different contexts ...

What am I doing wrong?

+1  A: 

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.

Marcus S. Zarra
You are right, the managed object context for one of them is nil. I have no idea why. Here is the code I tried: self.action = [NSEntityDescription insertNewObjectForEntityForName:@"MobileObjectAction" inManagedObjectContext:managedObjectContext]; self.user = [NSEntityDescription insertNewObjectForEntityForName:@"MobileUser" inManagedObjectContext:managedObjectContext];Then I print out the managedObjectContext for both.The user object has the valid managed object context but the action object just shows 0x0. Why is this happening??
Mike
Clearly at some point the managedObjectContext iVar is nil. I would put an assertion before both of those calls and catch it when it is nil. Then you can backtrace it to determine why.
Marcus S. Zarra