从OC到Swift(5)- 动态性,KVC\KVO

匿名 (未验证) 提交于 2019-12-03 00:08:02

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")
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!