解决方法
我的建议是使用KVC.也许不是最优雅的解决方案,但在概念上是KVC的逻辑应用.
观察属性的更改.注册init中的更改(entity:insertIntoManagedObjectContext :)或者在awakeFromFetch和awakeFromInsert中更好,并删除willTurnIntoFault中的观察者.
init(entity: NSEntityDescription!,insertIntoManagedObjectContext context: NSManagedObjectContext!) { super.init(entity: entity,insertIntoManagedObjectContext: context) addObserver(self,forKeyPath: "attribute",options: NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Old,context: nil) } override func observeValueForKeyPath(keyPath: String!,ofObject object: AnyObject!,change: NSDictionary!,context: CMutableVoidPointer) { if (keyPath == "attribute") { // do what you need to do } }
针对Swift 3进行了更新:
init(entity: NSEntityDescription!,options: [.old,.new],context: nil) } override func observeValue(forKeyPath keyPath: String?,of object: Any?,change: [NSKeyValueChangeKey : Any]?,context: UnsafeMutableRawPointer?) { if keyPath == "attribute" { // do what you need to do } }