KeyPath
KeyPath的语法为\Type.property.property.....
let nameCountAccessor = \Animal.name.count
现在可以使用KeyPath以一种新的姿势实现KVC和KVO了。
KVC
class Persion {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
let one = Persion(name: "AB", age: 10)
let path = \Persion.name
//设置name的值
one[keyPath: path] = "CD"
print(one[keyPath: path])//CD
Swift4中,可以对结构体进行KVC操作。
struct ValueType {
var name: String
}
var obj = ValueType(name: "yu")
let name = \ValueType.name
//set kvc
obj[keyPath: name] = "hua"
//get
print(obj[keyPath: name])//hua
KVO
@objcMembers class Student: NSObject {
dynamic var name: String
init(name: String) {
self.name = name
}
}
let stu = Student(name: "a")
let ob: NSKeyValueObservation! = stu.observe(\.name) { (ob, changed) in
print(ob.name)//aaa
}
stu.name = "aaa"
注意点:
- 只有继承于NSObject的Swift类才能实现KVO。
- Swift类必须增加关键字@objcMembers
- 要监听的属性,必须用dynamic修饰
- 如果使用的是闭包,则闭包需要自行保持引用,否则会被释放
网友评论