首页 > 解决方案 > NSPersistentStoreRemoteChangeNotification 没有被解雇

问题描述

我正在尝试在我的 CoreData+CloudKit 项目中执行历史跟踪,该项目使用NSPersistentCloudKitContainer. 我一直在关注 Apple 的示例项目

我想在远程存储更新后执行某些任务。为此,苹果建议在应用程序的“签名和功能的后台模式”部分启用远程通知。

我已经为我的项目启用了历史跟踪,如 Apple 的示例项目所示。

    // turn on persistent history tracking
    let description = container.persistentStoreDescriptions.first
    description?.setOption(true as NSNumber,
                           forKey: NSPersistentHistoryTrackingKey)

    // ...

我也注册了我的商店来监听商店的变化。

    // turn on remote change notifications
    let remoteChangeKey = "NSPersistentStoreRemoteChangeNotificationOptionKey"
    description?.setOption(true as NSNumber,
                               forKey: remoteChangeKey)

    // ...

还添加了观察者来监听NSPersistentStoreRemoteChangeNotification

然而,没有NSPersistentStoreRemoteChangeNotification被解雇。为了确保我的实现没有错误,我只是在@objc func storeRemoteChange(_ notification: Notification)Apple 提供的示例代码中放置了断点,但我仍然看不到任何通知被触发并且没有断点被激活。

我已经了解在示例项目中完成的标签的重复数据删除,并尝试对其进行测试,但没有任何成功。这是 Apple 实施中的错误还是我缺少任何所需的设置?

标签: core-datacloudkitios13nspersistentcloudkitcontainer

解决方案


我的猜测是你正在观察容器而不是商店协调员,像这样添加你的观察者:

    NotificationCenter.default.addObserver(
        self, selector: #selector(type(of: self).storeRemoteChange(_:)),
        name: .NSPersistentStoreRemoteChange, object: container.persistentStoreCoordinator)

注意最后一个参数container.persistentStoreCoordinator

还有一个警告,这个通知会出现在所有不同的线程上,所以你要小心并发。只需在该方法中放置 5 秒睡眠,您就会在应用启动时看到 3 个不同的线程调用它。这可能就是为什么在示例中有一个historyQueuewith maxOperationCount1 来处理它的原因。

有些通知有NSPersistentHistoryTokenKeyuserInfo不确定为什么。


推荐阅读