Swift: custom setter for CoreData NSManagedObject

How to implement a custom setter for NSManagedObject in Swift. I need to complete the task before setting the NSMangedObject property.

+8
ios setter swift core-data
source share
2 answers

My recommendation would be to use KVC. This may not be the most elegant solution, but a conceptually logical KVC application.

Watch for an attribute change. Register to change to init(entity:insertIntoManagedObjectContext:) or maybe better to awakeFromFetch and awakeFromInsert , and remove the observer in 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 } } 

Updated for Swift 3:

 init(entity: NSEntityDescription!, insertIntoManagedObjectContext context: NSManagedObjectContext!) { super.init(entity: entity, insertIntoManagedObjectContext: context) addObserver(self, forKeyPath: "attribute", 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 } } 
+7
source share

There is an even simpler way to do this without managing your KVO subscription. This can be done simply by overriding didChangeValueForKey: as follows:

  override func didChangeValueForKey(key: String) { super.didChangeValueForKey(key) if key == "propertyName" { // do something now when propertyName changed } } 
+6
source share

All Articles