dynamic
- 被@objc dynamic 修饰的内容会具有动态性,比如调用方法会走runtime那一套流程
class Dog: NSObject { @objc dynamic func test1() {} func test2() {} } var d = Dog() d.test1() d.test2()
- 对应汇编
KVC\KVO
- Swift支持KVC\KVO的条件
- 属性所在的类、监听器最终继承自NSObject
- 用@objc dynamic 修饰对应的属性
class Observer: NSObject { override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { print("observeValue", change?[.newKey] as Any) } }
class Person: NSObject { @objc dynamic var age: Int = 0 var observer: Observer = Observer() override init() { super.init() self.addObserver(observer, forKeyPath: "age", options: .new, context: nil) } deinit { self.removeObserver(observer, forKeyPath: "age") } } var p = Person() // observeValue Optional(20) p.age = 20 // observeValue Optional(25) p.setValue(25, forKey: "age")
block方式的KVO
class Person: NSObject { @objc dynamic var age: Int = 0 var observation: NSKeyValueObservation? override init() { super.init() observation = observe(\Person.age, options: [.new, .old]) { (person, change) in print(change.newValue as Any) } } } var p = Person() // Optional(20) p.age = 20 // Optional(25) p.setValue(25, forKey: "age")
来源:51CTO
作者:songzhuo1991
链接:https://blog.csdn.net/songzhuo1991/article/details/100982187