gpt4 book ai didi

ios - Today Extension 更改后刷新应用程序上的 CoreData

转载 作者:行者123 更新时间:2023-11-30 12:48:01 24 4
gpt4 key购买 nike

我有一个使用今日小部件的应用程序。它通过使用组来共享数据。目前它正在小部件中正确显示数据。如果我更改应用程序上的数据然后显示小部件,它会正确更新。现在,我想更新小部件上的一些数据并将其反射(reflect)在应用程序上。

该应用程序上有一个 UITableView,因此我使用 NSFetchedResultsController 来获取表中的数据。该小部件在 fetchedResultsController 中的项目之间滚动,并显示数据。在小部件上可以更新任意数量的项目。

我知道这是可以做到的,因为我已经在其他应用程序上看到过它。我只是不知道如何让应用程序知道我何时更新了小部件上的数据,以便可以刷新它。

至于我尝试过的,不多,因为我想不出要尝试什么。我确实添加了这个:

func controllerDidChangeContent(controller: NSFetchedResultsController) {
print ("Controller changed")
}

当我更改应用程序上的数据时会触发此事件,但当更改小部件中的数据时不会触发此事件。

根据下面的建议,我将以下代码添加到应用程序上的 viewDidLoad 中:

    let center = NSNotificationCenter.defaultCenter()

center.addObserver(self, selector: #selector(self.contextUpdated(_:)),name: NSManagedObjectContextDidSaveNotification,
object: context)

然后捕获通知:

@IBAction func contextUpdated(notification: NSNotification) {
print("Notification recieved")
}

我得到了与controllerDidChangeContent事件相同的结果 - 它在更改应用程序上的数据时触发,但我从小部件中没有得到任何结果。我的理解是小部件和应用程序不在同一个容器中,这就是我没有收到通知的原因。

我注意到的另一件事是,一旦我在小部件上保存了数据,应用程序上的 moc 就不再允许我使用它保存数据。也许是因为小部件上的上下文更新了数据并使应用程序上的上下文无效?

最佳答案

保存 moc 后,

NSFetchedResultsController 应该会自动更新。但是,您也可以在保存特定实体和属性等的 moc 时订阅更改。下面的示例代码可帮助您入门。订阅更改后,您可以过滤出更改的内容,提取对象,然后相应地更新您的表。

let center = NotificationCenter.default

center.addObserver(self,
selector: #selector(CLASS_NAME_HERE.contextUpdated(_:)),
name: NSNotification.Name.NSManagedObjectContextDidSave,
object: context)

// we would like to get notified for all changes to the given entity
// if you need more specific data, update the predicate as needed
let entityPredicate = NSPredicate(format: "entity.name == %@", ENTITIY_NAME_HERE)

func contextUpdated(_ notification: Notification) {
// all changes (inserted, updated, deleted) to the moc matching the predicate are inside notification
print("\(notification)
}

您可以按如下方式过滤通知。下面是插入的,但也可以轻松修改以获取更新和删除的对象。

let info = (notification as NSNotification).userInfo
if let set = info?[NSInsertedObjectsKey] as? NSSet, let insert = set.allObjects as? [NSManagedObject] {
let inserted = insert.filter { return predicate.evaluate(with: $0) }
}

关于ios - Today Extension 更改后刷新应用程序上的 CoreData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41374053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com