使用以下代码:
CustomObject *customObject = [[CustomObject alloc] initWithContext:self.persistentContainer.viewContext];
customObject.name = @"TEST";
customObject.customID = 1234;
NSManagedObjectContext *firstContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
firstContext.parentContext = self.persistentContainer.viewContext;
CustomObject *contextObj = [firstContext objectWithID:customObject.objectID];
NSError *error;
[self.persistentContainer.viewContext save:&error];
NSLog(@"ERROR [%@", error);
NSLog(@"NAME [%@]", contextObj.name);
我得到结果:
ERROR [(null)
[error] error: API Misuse: Attempt to serialize store access on non-owning coordinator (PSC = 0x6000015fa300, store PSC = 0x0)
CoreData: error: API Misuse: Attempt to serialize store access on non-owning coordinator (PSC = 0x6000015fa300, store PSC = 0x0)
NAME [(null)]
我试图理解为什么出现此警告。我希望在保存主上下文之后,我仍然能够在其子上下文上访问对象的属性,而不会出现任何问题。
有趣的部分是,如果我在保存主上下文之前取消对contextObj的操作,则一切正常:
CustomObject *customObject = [[CustomObject alloc] initWithContext:self.persistentContainer.viewContext];
customObject.name = @"TEST";
customObject.customID = 12234;
NSManagedObjectContext *firstContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
firstContext.parentContext = self.persistentContainer.viewContext;
CustomObject *contextObj = [firstContext objectWithID:customObject.objectID];
NSError *error;
NSLog(@"NAME [%@]", contextObj.name);
[self.persistentContainer.viewContext save:&error];
NSLog(@"ERROR [%@", error);
NSLog(@"NAME [%@]", contextObj.name);
NAME [TEST]
ERROR [(null)
NAME [TEST]
任何关于为什么发生这种情况的想法都将受到赞赏。 谢谢。