如何注意到核心数据处理的托管对象实体的变化? [英] How to notice changes on Managed Object Entity handled by Core Data?

查看:64
本文介绍了如何注意到核心数据处理的托管对象实体的变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

动机是要根据Entity值的更改重新计算。

Motivation is to get a trigger for recalculation upon changes on values of Entity.

下面引用的我的快速解决方案是可行的,但它有缺点。效率低下。

My quick solution cited below works, but it has drawbacks. It is inefficient.

在实际的应用中,有数十个实体。对它们的任何更改都会导致不必要的通知。

In actual App, there are tens of entities. Changes on any of them will cause unnecessary notifications. Those could be avoided, if possible.

在此示例中,唯一的EmployeeMO感兴趣。

In this example, the only EmployeeMO is interested. No other entity needs to be observed.

您的想法是什么?

let n = NotificationCenter.default
n.addObserver(self, selector: #selector(mocDidChange(notification:)),
              name: NSNotification.Name.NSManagedObjectContextObjectsDidChange,
              object: managedObjectContext)

@objc func mocDidChange(notification n: Notification) {
  if n.isRelatedTo(as: EmployeeMO.self) {
    // do recalculation
  }
}

还有一个扩展名,用于检查通知是否与给定的管理对象有关:

And an extension to check if the notification is related to a given managed object:

extension Notification {

  public func isRelatedTo<T>(as t: T.Type) -> Bool where T: NSManagedObject {

    typealias S = Set<T>

    let d = userInfo as! [String : Any]

    return d[NSInsertedObjectsKey] is S ||
      d[NSUpdatedObjectsKey] is S ||
      d[NSDeletedObjectsKey] is S ||
      d[NSRefreshedObjectsKey] is S ||
      d[NSInvalidatedObjectsKey] is S
  }

}

Xcode 9 Beta,Swift 4

Xcode 9 Beta, Swift 4

谢谢。

推荐答案

是一个内置对象,已经完全可以做到这一点- NSFetchedResultsController 。它旨在与tableview或collectionView一起使用,但没有一个就可以正常工作。它足够轻便,可以安全地仅用于一个对象。

The is a built in object that does exactly this already - NSFetchedResultsController. It is designed to work with a tableview or collectionView, but can work fine without one. It is lightweight enough that it is safe to use for just one object.

这篇关于如何注意到核心数据处理的托管对象实体的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆