Using property observers on NSManaged vars

2020-08-09 08:15发布

问题:

I have a var declared in a class like so:

@NSManaged var isFavorite: Bool

I would like to declare a property observer, very similar to the one below.

 var organization: String {
        didSet { postNotificationWithName( "newData" ) }
    }

However, Swift tells me that having property observers on NSManaged vars is not allowed. Is there any way I can implement such a feature or something similar for my isFavorite variable?

回答1:

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.



回答2:

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>) {


回答3:

Override NSManagedObject's func didChangeValue(forKey key: String) see (https://developer.apple.com/documentation/coredata/nsmanagedobject/1506976-didchangevalue)