我正在使用 UIManagedDocument 来获取核心数据。我的 ManagedObjectContext 中有日历对象,其 calendarSelected
属性。 Calendar 实体与 CalendarEntry 具有一对多关系。
当我改变他们的calendarSelected
时属性,然后执行 NSFetchRequest 以获取具有以下谓词的 CalendarEntry 对象:
[NSPredicate predicateWithFormat:@"calendar.calendarSelected = YES"]
calendar.calendarSelected 似乎没有看到我在没有调用的情况下所做的更改
[myManagedDocument saveToURL:myManagedDocument.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:^(BOOL success) {}];
更新:
当日历事件关系出现故障时,似乎会发生这种情况:calendarEvents = "<relationship fault: 0x91aec90 'calendarEvents'>";
但当关系没有过错时有效。
最佳答案
如果问题仅发生在一对多关系指向的新插入的 CalendarEntry 对象上,则它们可能还没有永久对象 ID。只需转储对象 ID 并检查它是临时的还是永久的,就可以轻松调试。
当保留一对多关系中的包含对象时,我见过这种情况发生;似乎只要保留它,关系中包含的多对多对象就永远不会达到获得永久 ID 的程度。通过将应用程序置于后台并重新启动,调试起来比较容易;后台通常会强制 UIManagedDocument 保存,此后事情将开始按您的预期工作,因为 CalendarEntry 实体将被分配永久 ID,因此将变得可获取。
就保存 UIManagedDocument 而言,您无法控制使用 UIManagedDocument 时何时发生。最好的办法是通过 updateChangeCount:UIDocumentChangeDone 安排将来进行保存,但同样,它会“很快”发生,但不是确定性的,即,不可能知道它何时会发生。
要解决临时对象 ID 与永久对象 ID 问题,如果您遇到这种情况,请在 NSManagedObjectContext 上尝试以下类别;在完成插入新的 CalendarEntry 对象后调用它,以强制解决该问题。
// Obtain permanent ids for any objects that have been inserted into
// this context.
//
// As of this writing (iOS 5.1), we need to manually obtain permanent
// ids for any inserted objects prior to a save being performed, or any
// objects that are currently retained, that have relationships to the
// inserted objects, won't be updated with permanent ids for the related
// objects when a save is performed unless the retained object is refetched.
// For many objects, that will never occur, so we need to force the issue.
- (BOOL)obtainPermanentIDsForInsertedObjects:(NSError **)error
{
NSSet * inserts = [self insertedObjects];
if ([inserts count] == 0) return YES;
return [self obtainPermanentIDsForObjects:[inserts allObjects]
error:error];
}
关于ios - NSFetchRequest 没有看到 NSManagedObjectContext 中关系的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10114951/