Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using property observers on NSManaged vars

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?

like image 722
Satre Avatar asked May 13 '15 00:05

Satre


1 Answers

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.

like image 104
Tom Harrington Avatar answered Oct 03 '22 16:10

Tom Harrington