swift中kvo的使用
class MyClass: NSObject {
dynamic var date = Date()
}
class MyClass1: NSObject {
var date = Date()
}
class MyChildClass: MyClass1 {
dynamic override var date: Date {
get { return super.date }
set { super.date = newValue }
}
}
private var myContext = 0
class Class: NSObject {
var myObject: MyClass!
override init() {
super.init()
myObject = MyClass()
print("初始化 MyClass达址,當前日期: \(myObject.date)")
myObject.addObserver(self,
forKeyPath: "date",
options: .new,
context: &myContext)
delay(3) {
self.myObject.date = Date()
}
}
override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?)
{
if let change = change, context == &myContext {
let newDate = change[.newKey]
print("日期發(fā)生變化 \(newDate)")
}
}
}
let obj = Class()
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者