swift5 KVO KVC KeyPath

2019-08-22  本文已影响0人  hhcszgd
extension AppDelegate {
    func testKeyPath() {
//        testKVO()
         testDog()
        testCat()
    }
    func testKVO()   {
        let p = Person()
        p.name = "0000"
        self.p = p
        let a = p.observe(\Person.name, options: NSKeyValueObservingOptions.new) { (person , change ) in
            print("\(person.name ) , \(change)")
        }
        self.o = a
        DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 5) {
            self.p.name = "xxxx"
        }
    }
    
    func testDog() {
        let dog = Dog()
        let nameKeypath = \Dog.name // ReferenceWritableKeyPath<Dog, String>
        let name = dog[keyPath : nameKeypath]
        print("dog name is : \(name)")
        SwiftUIUsage.testKeyPath(m: dog, s: \Dog.number )
    }
    func testCat() {
        //        KeyPath
        let cat = Cat()
        //        setter(for: d, keyPath: \Dog.name)
        let nameKeypath = \Cat.name // WritableKeyPath<Cat, String>
        let name = cat[keyPath : nameKeypath]
        
        let birthdayKeypath = \Cat.birthday // KeyPath<Cat, String>
        let birthday = cat[keyPath : birthdayKeypath]
        print("cat name is : \(name)")
        print("cat birthday is : \(birthday)")
        SwiftUIUsage.testKeyPath(m: cat, s: \Cat.name )
    }
}
///另外一件事就是被观察的属性 需要用 dynamic 修饰 ,否则也无法观察到。
@objcMembers
class Person : NSObject {
    ///一定要加@objc dynamic 才能实现这个属性的kvo
    ///或者在类声明的时候 , 在class前加上@objcMembers 关键字 , 且在被观察的属性前加dynamic
//    @objc dynamic
    dynamic var name : String = "default dog"
}

func setter<Object: AnyObject, Value>( for object: Object,  keyPath: ReferenceWritableKeyPath<Object, Value>
) -> (Value) -> Void {
    return { [weak object] value in
        object?[keyPath: keyPath] = value
    }
}
class Dog : NSObject{
     var name = "default"
    var number = "dog's telephone number : 18818181818"
}
struct Cat  {
    var name = "default cat"
    let birthday = "2019-11-11"
}

func testKeyPath<MMMM>(m : MMMM ,s : KeyPath<MMMM , String>)  {
    let exept = m[keyPath : s]
        print(exept)
}

上一篇下一篇

猜你喜欢

热点阅读