0
votes

I inserted an object in child context and got the objectID, then I saved both child context and parent context. now I want to get the object through objectID, but I can only get it with child context but parent context, why?

...
NSManagedObjectContext *childContext = [[[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType] autorelease];
childContext.parentContext = self.parentContext;
[childContext performBlock:^{
    NSManagedObject *obj = [NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:childContext];

    if (![childContext save:&error]) {
        NSLog(@"%@", error);
    }

    [self.parentContext performBlockAndWait:^{
        if (![self.parentContext save:&error]) {
            NSLog(@"%@", error);
        }
    }];

    NSManagedObjectID *objID = [obj ObjectID];
    NSManagedObject *objTmp = [self.parentContext existingObjectWithID:objID error:&error];
    // Why objTmp is nil here?

    NSManagedObjectID *objIDTmp = [[[self.parentContext executeFetchRequest...] objectatindex:0] objectID];
    // objIDTmp is different from objID 
}];
2

2 Answers

0
votes

A new object will get a new NSManagedObjectID when it is saved to the permanent store. You can call obtainPermanentIDsForObjects to get a permanent id before saving it.

[childContext obtainPermanentIDsForObjects:@[obj] error:&error];
NSManagedObjectID *objID = [obj ObjectID];
0
votes

The NSManagedObjectID of a newly created NSManagedObject that has not been committed will change after the save is performed.

That's the reason you are not able to find the NSManagedObject using objID after saving the object.

Read Managed Object IDs and URIs