保存后,在子上下文中创建的新对象在父上下文中不存在

Yuwen Yan

我在子上下文中插入一个对象并获得了objectID,然后保存了子上下文和父上下文。现在我想通过objectID获取对象,但是我只能通过子上下文获取它,但是只能通过父上下文获取它,为什么?

...
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 
}];
埃里克·赫斯特伦(Eric Hedstrom)

将新对象保存到永久存储后,它将获得新的NSManagedObjectID。您可以先致电obtainPermanentIDsForObjects获取永久性ID,然后再保存它。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

在静态上下文中,当前上下文中不存在某些名称

来自分类Dev

名称在当前上下文中不存在

来自分类Dev

当前上下文中不存在名称“ ConfigureAuth”

来自分类Dev

变量在当前上下文中不存在

来自分类Dev

名称SpaceProcessingModeValues在此上下文中不存在

来自分类Dev

WebApiConfig在当前上下文中不存在

来自分类Dev

itemToDto在当前上下文中不存在

来自分类Dev

当前上下文中不存在“ UnityShim”

来自分类Dev

当前上下文中不存在变量?

来自分类Dev

名称“”在当前上下文中不存在

来自分类Dev

在当前上下文中不存在控件

来自分类Dev

错误:在当前上下文中不存在

来自分类Dev

XmlDocument在当前上下文中不存在

来自分类Dev

GetEnumerator在此上下文中不存在

来自分类Dev

_adapater在当前上下文中不存在

来自分类Dev

Gridview在当前上下文中不存在

来自分类Dev

当前上下文中不存在 mvx

来自分类Dev

当前上下文中不存在名称“name”

来自分类Dev

当前上下文中不存在名称 htmlMessageBody

来自分类Dev

当前上下文中不存在名称“Monsters”

来自分类Dev

当前上下文中不存在名称“img”

来自分类Dev

当前上下文中不存在 ViewContext

来自分类Dev

属性在当前上下文中不存在

来自分类Dev

当前上下文中不存在名称“Master”

来自分类Dev

当前上下文中不存在名称属性?

来自分类Dev

在当前上下文中不存在

来自分类Dev

当前上下文中不存在名称“表”

来自分类Dev

当前上下文中不存在名称“FileUtil”

来自分类Dev

当前上下文中不存在名称“LikeShop”