临时托管对象ID和子托管对象上下文

时间:2011-08-14 03:45:11

标签: cocoa core-data

我在Lion中使用了一个新功能,子管理对象上下文:“管理可丢弃的编辑,例如在检查器窗口或视图中。”

当我从父MOC向子MOC传递托管对象ID时,如果从未保存过父MOC,我将收到错误:“尝试访问商店中未找到的对象。”

NSManagedObjectContext *parentContext = [(NSPersistentDocument *)[[[self window] windowController] document] managedObjectContext];

self.subMOC = [[[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType] autorelease];

[subMOC setParentContext:parentContext];

NSManagedObjectID *objectValueID = [[[self superview] valueForKey:@"objectValue"] objectID];

self.subObjectValue = [subMOC existingObjectWithID:objectValueID error:&err];

如果文档已保存,则上述工作正常。如果尚未保存,我有哪些选择?

2 个答案:

答案 0 :(得分:2)

在保存MOC之前,任何对象ID都是临时的,您必须保存上下文以获取“真实”对象ID。我不知道这个。

编辑:

我的意思是,显然你可以做到

if (parentContext.hasChanges) {
      [panrentContext save:nil];
}

答案 1 :(得分:0)

答案,无需保存,是使用获取请求。这段代码非常接近文档中的内容,对我有用:

NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity" inManagedObjectContext:subMOC];
[request setEntity:entity];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self == %@", [[self superview] valueForKey:@"objectValue"]];
[request setPredicate:predicate];

err = nil;
NSArray *array = [subMOC executeFetchRequest:request error:&err];
if (array != nil)
{
   self.subObjectValue = [array objectAtIndex:0];
}

在我的项目中,我仍然使用上述问题中的代码,只有在失败时才使用获取请求。