CoreData(+ iCloud)产生无效的模型状态

CoreData (+ iCloud) produces invalid model state

我正在使用 CoreData 和 iCloud 在设备之间同步数据。

每次 iCloud 导入后(观察 NSPersistentStoreDidImportUbiquitousContentChangesNotification),我 运行 一个简单的重复数据删除算法来查找和删除重复数据。 保存更改后,我在控制台中看到来自 CoreData 的警告,即特定实体实例(已被重复数据删除算法删除)的所有属性和关系都替换为 nil/0.

CoreData: warning: An NSManagedObjectContext delegate overrode fault handling behavior to silently delete the object with ID '0xd000000000040006 <x-coredata://ADDDABCD-4891-4DCF-B55B-53AA64D11922/<ENTITY_NAME>/p1>' and substitute nil/0 for all property values instead of throwing.

问题是此实体中的一种关系不是可选的,这会在下次 iCloud 想要在其他设备上导入这些更改时产生错误。

-[_PFUbiquityRecordsImporter operation:failedWithError:](979): CoreData: Ubiquity:  Import operation encountered had trouble importing log file, Error Domain=NSCocoaErrorDomain Code=134302 "The operation couldn’t be completed. (Cocoa error 134302.)" 
[...], an error occurred saving changes to the persistent store mutated during the import process. [...] 
"The operation couldn’t be completed. (Cocoa error 1560.)"} User Info: { [...] 
NSValidationErrorObject=<NSManagedObject: 0x1742c7bd0> (entity: <ENTITY_NAME>; [...] 
{NSValidationErrorKey=<NON-OPTIONAL_RELATIONSHIP_NAME> [...] 
"Error encountered while importing transaction log at URL: ...

如何避免所有属性都设置为 nil/0?

我是怎么解决的

我最大的错误是我处理 NSPersistentStoreDidImportUbiquitousContentChangesNotification 通知的方式。 我只合并了 "main" 上下文中的更改(在主线程中使用)。但是我忘了将更改合并到我的第二个 "root" 上下文(NSPrivateQueueConcurrencyType 类型)中,我也用它来将上下文保存到持久存储中,并且它是 "main" 上下文的父级.

在不了解内部结构的情况下,我怀疑因为我的 "root" 上下文不知道无处不在的内容更改,所以下次我保存更改时生成的事务日志(写入 iCloud)不一致。现在我将更改通知合并到我的 "root" 和 "main" 上下文中,事情开始变得更好。