Hokage Hokage - 15 days ago 5
iOS Question

Swift: Custom Setter For CoreData NSManagedObject

How to implement custom setter for

NSManagedObject
in Swift. I need to do task before setting the
NSMangedObject
Property.

Answer

My recommendation would be to use KVC. Maybe not the most elegant solution, but conceptionally a logical application of KVC.

Observe a change of the attribute. Register for the change in init(entity:insertIntoManagedObjectContext:) or maybe better in 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
    }
}