在NSManaged vars上使用属性观察器

时间:2015-05-13 00:18:54

标签: ios swift nsmanagedobject observers

我在类中声明了var:

@NSManaged var isFavorite: Bool

我想声明一个属性观察者,非常类似于下面的那个。

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

然而,Swift告诉我,不允许在NSManaged vars上拥有财产观察员。有什么方法可以为我的isFavorite变量实现这样的功能或类似功能吗?

3 个答案:

答案 0 :(得分:26)

是 - 删除// Note the minus sign. physicsWorld.gravity = CGVector(dx: 0, dy: -9.8) 。这不是绝对必要的,但如果您删除它,您很遗憾需要为该属性实施@NSManagedget。您需要添加类似

的内容
set

如果你实际上并不需要它们,那么实施这两种方法会很烦人,但现在就是这样。

由于您将拥有public var newData: String? { set { self.willChangeValue(forKey: "newData") self.setPrimitiveValue(newValue, forKey: "newData") self.didChangeValue(forKey: "newData") } get { self.willAccessValue(forKey: "newData") let text = self.primitiveValue(forKey: "newData") as? String self.didAccessValue(forKey: "newData") return text } } ,因此您可能不需要set,但如果需要,您仍然可以添加didSet

答案 1 :(得分:2)

糟糕!保罗帕特森是对的。您应该使用的是Key Value Observing - 这正是它在我建议的链接中应该做的。

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

另见swift notes: https://developer.apple.com/library/mac/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html (使用页面右上角的“在此页面上”菜单进行键值观察)

类似

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

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

答案 2 :(得分:-1)