核心数据 + iCloud 同步 NSPersistentStoreDidImportUbiquitousContentChangesNotification

Core data + iCloud Sync NSPersistentStoreDidImportUbiquitousContentChangesNotification

我遇到了核心数据和 iCloud 同步的一些有线行为。我向我的应用程序添加了 iCloud 文档和 Cloudkit 功能,并订阅了这三个通知:

NSPersistentStoreCoordinatorStoresWillChangeNotification
NSPersistentStoreCoordinatorStoresDidChangeNotification
NSPersistentStoreDidImportUbiquitousContentChangesNotification

我第一次 运行 我收到这些通知的应用程序:

Using local storage: 1
store will Change notification
store did Change notification
Using local storage: 0

但是,NSPersistentStoreDidImportUbiquitousContentChangesNotification 没有被触发,因为核心数据没有从我的 iCloud 帐户的无处不在的容器中下载数据。

然而,当我退出应用程序并重新启动它时,即使打开了飞行模式,我的所有数据也会立即加载。似乎数据已在第一次启动时下载并保存到 SQLite 存储,但未触发通知,因此我的 UI 可以刷新。

以前有没有人经历过这种情况,你在那种情况下做了什么。

首次设置和 'normal' 同步操作之间存在差异。

NSPersistentStoreDidImportUbiquitousContentChangesNotification 首次设置时未发布;只有在以后发生变化时。这会通知应用导入它们(通过调用 mergeChangesFromContextDidSaveNotification(_:))。

Apple 的 iCloud Programming Guide for CoreData 非常有助于理解在哪个阶段发生了什么。

请特别参阅有关 iCloud Performs a One-Time Setup and Core Data Posts Content Changes from iCloud 的章节。