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

Posted

技术标签:

【中文标题】CoreData (+ iCloud) 产生无效的模型状态【英文标题】:CoreData (+ iCloud) produces invalid model state 【发布时间】:2015-02-27 10:28:19 【问题描述】:

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

【问题讨论】:

【参考方案1】:

我是如何解决的。

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

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

【讨论】:

嗨!你能详细说明你是怎么做到的吗?谢谢。

以上是关于CoreData (+ iCloud) 产生无效的模型状态的主要内容,如果未能解决你的问题,请参考以下文章

iCloud 与 Coredata 同步

iCloud 和 CoreData:更改为 iCloud Store 时的通知(使用现有 iCloud 数据首次启动)

Coredata、NSOrderedSet 和 iCloud

在使用 Ensembles 进行 CoreData 和 iCloud 同步之前,我是不是需要任何 iCloud 设置?

CoreData 与 iCloud,不与同步通知一起使用

iOS:SharedCoreData 示例代码 (iCloud + CoreData) |如何合并更改