ios - NSFetchRequest 没有看到 NSManagedObjectContext 中关系的变化

标签 ios core-data

我正在使用 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/

相关文章:

ios - 按下导航栏的编辑按钮时,如何使 TableView Cell 中的 textField 可编辑?

ios - 如何为 iOS 的 FirebaseUI 登录添加背景图片?

ios - 使用 Xcode 13.3 构建时,格式化程序损坏的 SwiftUI TextField?

objective-c - 保存核心数据模型因断电中断 : Persistent store migration failed, 缺少映射模型

ios - 核心数据未保存在分发版本中

ios - 导入开发人员配置文件 .developerprofile 不起作用。仍然需要密码

android - ListView 中的 ListView 不滚动

ios - 核心数据 - 获取请求结果与谓词不匹配

Swift:如何在 Core Data 中进行过滤

cocoa - 隐藏核心数据高级设置警告