WWDC-2017笔记---KVC和KVO

WWDC,iOS,KVC,KVO

Posted by Karim on September 11, 2017

swift3的时候,如果想使用KVC需要把类声明是@objcMembers,和将成员变量声明为dynamic,然后就可以使用objc中的value(forKey key: String)setValue(_ value: Any?, forKey key: String),但是只支持继承NSObject的类,换句话说,是不支持struct

@objcMembers class Kid: NSObject {
    
  dynamic  var name = String()
    
}
var kid = Kid()
kid.name = "张三"
print(kid.value(forKey: "name")!)
kid.setValue("李四", forKey: "name")
print(kid.value(forKey: "name")!)

在swift4中,可以通过KeyPath间接访问成员变量,达到KVC的效果。

  let person = Person() //结构体
  let name = person[keyPath:\Person.name] //get
  person[keyPath:\Person.name] = "张三" //set

KVO的使用也是基于KVC的KeyPath基础上使用

 class ViewController: UIViewController {
    var kid = Kid()
    var observation: Any? = nil //负责监听kid

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        //监听kid的name
        self.observation = kid.observe(\Kid.name, changeHandler: { (object, change) in
            debugPrint("\(object) + \(change)")
        })
    }
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    kid.name = "hello"
   
    }
}

想了解的更多,可以看Session 212


请保持转载后文章内容的完整,以及文章出处。本人保留所有版权相关权利。

分享到: