【问题标题】:NSPersistentCloudKitContainer and persistent history trackingNSPersistentCloudKitContainer 和持久历史跟踪
【发布时间】:2022-06-14 19:36:28
【问题描述】:

我正在构建一个使用NSPersistentCloudKitContainer 的应用程序。该应用程序没有共享功能,其唯一的后端功能是使用 cloudkit 容器在用户的设备之间同步数据。设置相当简单,实例化一个容器,设置单个商店描述,然后加载商店。

我的大问题:我需要对持久历史跟踪做任何事情吗?我还没有找到这个问题的具体答案,但据我所知,持久历史跟踪用于将一个目标中发生的更改(例如扩展)合并到另一个目标中。听起来我不需要它来充分利用 iCloud 同步。

【问题讨论】:

  • 我相信持久历史记录用于与所有外部更改同步,例如应用程序扩展或远程数据库 (CloudKit)
  • 您会在最近发现这一点(很抱歉,我无法引用它何时生效),但每个NSPersistentCloudKitContainer 都会自动实现NSPersistentHistoryTracking。您可能需要注意的是,如果您的商店(例如 sqlite 文件)在您实施 NSPersistentCloudKitContainer 之前已经存在(即它只是 NSPersistentContainer),那么历史跟踪将不会自动实施,因此只会新插入对象将注册到 CloudKit。
  • 这听起来很对,我只是找不到任何可以证实这种情况的东西

标签: swift core-data nspersistentcloudkitcontainer


【解决方案1】:

您确实需要启用持久历史跟踪,以便您的设备(如果用户禁用您的应用使用 iCloud,如果他们重新启用它,则能够赶上它。执行以下操作:

@objc func initCoreDataStack()
{
    guard let description = pc.persistentStoreDescriptions.first else {
        fatalError("*** CoreDataUtil - could not find persistent store description.")
    }
    description.setOption(true as NSNumber, forKey:NSPersistentHistoryTrackingKey)
    description.setOption(true as NSNumber, forKey:NSPersistentStoreRemoteChangeNotificationPostOptionKey)

    //
    //  If user wants iCloud Storage set id, else set it to nil
    //  but with history on (see above) so that if they enable it
    //  later there is a history of changes.
    //
    if(useiCloud == true) {
        let cloudKitContainerIdentifier = "iCloud.your.container"
        let options = NSPersistentCloudKitContainerOptions(containerIdentifier:cloudKitContainerIdentifier)
        description.cloudKitContainerOptions = options
    }
    else {
        description.cloudKitContainerOptions = nil
    }
    //
    //  If DB is in old location move it to the default.
    //  Seems required to get CloudKit Sync to work.
    //
    moveCoreDataSqliteDBIfRequired(pc.persistentStoreCoordinator)
    
    pc.persistentStoreDescriptions.first?.url = storeURL()
    
    pc.viewContext.automaticallyMergesChangesFromParent = true
    pc.loadPersistentStores { _, error in
        if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
        // Set this here so that updates by consumers are dynamic
        self.pc.viewContext.automaticallyMergesChangesFromParent = true

        self.sendMOCReadyNotificationForPlatform()
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 2013-03-17
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多