Using property observers on NSManaged vars Using property observers on NSManaged vars swift swift

Using property observers on NSManaged vars


Yes-- delete the @NSManaged. It's not absolutely required, but if you delete it you unfortunately need to implement get and set for the property. You would need to add something like

The @objc is only needed if you want to be able to do KVO on the property.

@objc public var newData: String? {    set {        willChangeValue(forKey: "newData")        setPrimitiveValue(newValue, forKey: "newData")        didChangeValue(forKey: "newData")    }    get {        willAccessValue(forKey: "newData")        let text = primitiveValue(forKey: "newData") as? String        didAccessValue(forKey: "newData")        return text    }}

It's kind of annoying to implement both of these if you don't actually need them but that's the way it is for now.

Since you'll have a set, you might not need a didSet, but you can still add a didSet if you want one.


Whoops! Paul Patterson is right. What you're supposed to use is Key Value Observing - which is exactly what it says you're supposed to do in the link I suggested.

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html

See also swift notes:https://developer.apple.com/library/mac/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html(use the 'On This Page' menu at the top right of the page for Key-Value Observing)

So something like

objectToObserve.addObserver(self, forKeyPath: "organization", options: .New, context: &myContext)

paired with

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {