Using property observers on NSManaged vars

喜你入骨 提交于 2019-12-04 23:47:09
Tom Harrington

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>) {
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!