在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
创建完成的person类 @objc class Person: NSObject { @objc dynamic var name:String? init(name: String) { self.name = name; } KVC的使用 var person:Person! self.person = Person.init(name: "xiaoming") print("name:\(person.name)")//name:Optional("xiaoming") // 取值 var value = self.person.value(forKey: "name") as? String //name:Optional("xiaoming") print("name:\(value)")//name:Optional("xiaoming") //使用 self.person.setValue("xiaohua", forKeyPath: "name") print("name:\(person.name)")//name:Optional("xiaohua") //使用字典 let dict = ["name":"小光"] self.person.setValuesForKeys(dict) let dictOut = self.person.dictionaryWithValues(forKeys: ["name"]) print("\(dictOut)")//["name": 小光] KVO的使用 self.person.name = "xiaoming" self.person.addObserver(self, forKeyPath: "name", options: NSKeyValueObservingOptions.new, context: nil)// 监听(KVO的属性必须设置dynamic).addObserver(self, forKeyPath: "userName", options: NSKeyValueObservingOptions.new, context: nil)// 监听(KVO的属性必须设置dynamic) let deadline = DispatchTime.now() + 5.0 DispatchQueue.global().asyncAfter(deadline: deadline) { self.person.name = "xiaoxiao" } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if "name" == keyPath { print("之前的: \(String(describing: change?[.oldKey]))")//不知道为什么这里一直是nil if let newValue = change?[.newKey] { print("最新的: \(newValue)")//最新的: xiaoxiao } } }
|
请发表评论