我无法将核心数据同步到 CloudKit 的公共数据库。然而,私人数据库同步工作正常。
在设置
NSPersistentCloudKitContainer
时,我正在创建两个商店描述 - 一个用于公共和私人,使用具有这些名称的配置:
guard let description = container.persistentStoreDescriptions.first else {
fatalError("###\(#function): Failed to retrieve persistent store description")
}
let baseUrl = description.url!.deletingLastPathComponent()
let containerIdentifier = description.cloudKitContainerOptions!.containerIdentifier
// MARK: Private store
let privateDescription = NSPersistentStoreDescription(url: baseUrl.appendingPathComponent("private.sqlite"))
let privateOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: containerIdentifier)
privateOptions.databaseScope = .private
privateDescription.cloudKitContainerOptions = privateOptions
privateDescription.configuration = "Private"
privateDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
privateDescription.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
// MARK: Public store
let publicDescription = NSPersistentStoreDescription(url: baseUrl.appendingPathComponent("public.sqlite"))
let publicOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: containerIdentifier)
publicOptions.databaseScope = .public
publicDescription.cloudKitContainerOptions = publicOptions
publicDescription.configuration = "Public"
publicDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
publicDescription.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
container.persistentStoreDescriptions = [privateDescription, publicDescription]
当我保存一条应该同步到公共存储的记录时(在
managedObjectContext.saveIfChanged()
),它只保存在本地设备中,而不是 CloudKit 中,而在控制台输出中我看到一条关于忽略远程更改通知的消息:
CoreData: debug: CoreData+CloudKit: -[NSCloudKitMirroringDelegate remoteStoreDidChange:]_block_invoke_2(3048): <NSCloudKitMirroringDelegate: 0x600003c840e0> - Ignoring remote change notification because it's for a different store: <private store identifier> / <public store identifier>
我不明白为什么会这样(记录类型只存在于公共商店的配置中),非常感谢任何帮助!
我已经尝试专门将对象分配给公共存储,仔细检查,但仍然得到相同的调试消息并且没有数据存储在 CloudKit 中。
managedObjectContext.assign(forecastRequest, to: managedObjectContext.persistentStoreCoordinator!.persistentStores.first(where: { $0.configurationName == "Public" })!)
事实证明“忽略远程更改”消息是无关的。
在创建一个单独的测试项目并向自己证明代码本身有效之后,通过更多的挖掘我发现了真正的错误:
"Invalid Arguments" (12/2016); server message = "Field '___modTime' is not marked sortable"
...通过在 CloudKit 控制台中向
SORTABLE
添加 modifiedTimestamp
索引来解决。我知道需要为公共模型添加 QUERYABLE
索引,但错过了 SORTABLE
.
数据现在可以按预期同步我的应用程序。