首页 > 解决方案 > NSFetchedResultsController 看不到扩展所做的插入

问题描述

我有一个这样的 iOS 应用程序

我的问题是,当我使用Intents Extension将某些内容插入 Core Data 时,它不会出现在Main Application的 UITableView 中,直到我像这样手动刷新 fetchedResultsController :

NSFetchedResultsController<NSFetchRequestResult>.deleteCache(withName: "myCache")
try? fetchedResultsController.performFetch()
tableView.reloadData()

有没有办法让 fetchedResultsController 看到更改而无需手动刷新所有内容?


注意:如果我从主应用程序向核心数据中插入一些内容,那么 fetchedResultsController 会自动看到更改并更新表(如预期的那样)

标签: iosswiftcore-datansfetchedresultscontroller

解决方案


要在应用程序和扩展程序之间共享数据库,您需要实现持久历史跟踪。有关介绍,请参阅WWDC 2017 What's New in Core Data at 20:49,有关示例代码,请参阅文档Consuming Relevant Store Changes

基本思想是启用 store 选项NSPersistentHistoryTrackingKey,观察NSPersistentStoreRemoteChangeNotification,在收到通知后,您应该使用获取更改,然后使用andNSPersistentHistoryChangeRequest合并到上下文中。然后您的遗嘱会相应更新。mergeChangesFromContextDidSaveNotificationtransaction.objectIDNotificationNSFetchedResultsController


推荐阅读