Motivation - get a trigger for recounting when Entity values โโchange.
My quick solution below works, but it has disadvantages. It is inefficient.
There are dozens of entities in the application itself. Changes to any of these will cause unnecessary notifications. They could have been avoided, if possible.
In this example, only EmployeeMO is interested. No other object needs observation.
What do you think?
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 a notification is associated with this managed entity:
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
Thanks.
source share