KVO对Swift的计算属性 [英] KVO on Swift's computed properties
问题描述
只是想知道在计算属性中是否可以在Swift 2.2中使用KVO!?
just wondering if this is possible in Swift 2.2, KVO on a computed property!?
ie:
var width = 0
var height = 0
private var area : Double {
get {
return with * height
}
}
self.addOberser(self, forKeyPath: "area", ......
客户端代码是修改with或height触发器observeValueForKeyPath吗?
Would a client code modifying the with or height trigger observeValueForKeyPath?
在参与市长之前检查一下类重构.KVO的语法很烦人,因为如果有人手头的答案(我假设答案是否定的),它甚至不值得去游乐场。
Just checking before engaging on a mayor class refactor. KVO's syntax being as annoying as it's is not worth even a playground if someone has an answer at hand (I am assuming answer is NO)
问候!
~d
regards! ~d
推荐答案
该代码无法运作有两个原因:
That code won't work for two reasons:
-
您必须将
动态
属性添加到区域
属性,如采用Cocoa设计模式在中使用Swift与Cocoa和Objective-C 。
You must add the
dynamic
attribute to thearea
property, as described in the section "Key-Value Observing" under "Adopting Cocoa Design Patterns" in Using Swift with Cocoa and Objective-C.
您必须声明 area
取决于 width
和 height
,如键值观察编程中的https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/KeyValueObserving/Articles/KVODependentKeys.html\"rel =noreferrer>注册从属关键字指南 。 (这适用于Objective-C和Swift。)为此,您还必须将 dynamic
添加到 width
和高度
。
You must declare that area
depends on width
and height
as described in "Registering Dependent Keys" in the Key-Value Observing Programming Guide. (This applies to Objective-C and Swift.) And for this to work, you also have to add dynamic
to width
and height
.
(你可以改为调用 willChangeValueForKey
和 didChangeValueForKey
每当 width
或 height
更改时,它就是通常更容易实现 keyPathsForValuesAffectingArea
。)
(You could instead call willChangeValueForKey
and didChangeValueForKey
whenever width
or height
changes, but it's usually easier to just implement keyPathsForValuesAffectingArea
.)
因此:
class MyObject: NSObject {
dynamic var width: Double = 0
dynamic var height: Double = 0
dynamic private var area: Double {
return width * height
}
class func keyPathsForValuesAffectingArea() -> Set<String> {
return [ "width", "height" ]
}
func register() {
self.addObserver(self, forKeyPath: "area", options: [ .Old, .New ], context: nil)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
print("observed \(keyPath) \(change)")
}
}
let object = MyObject()
object.register()
object.width = 20
object.height = 5
输出:
observed Optional("area") Optional(["old": 0, "new": 0, "kind": 1])
observed Optional("area") Optional(["old": 0, "new": 100, "kind": 1])
这篇关于KVO对Swift的计算属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!