美文网首页
Swift KVO和KVC底层实现原理

Swift KVO和KVC底层实现原理

作者: Johnson_9d92 | 来源:发表于2022-02-13 10:24 被阅读0次

    Swift KVO和KVC底层实现原理

    
    
    import Cocoa
    
    class SimpleClass {
        var someValue: String = "123"
    }
    //SimpleClass().setValue("456U", forKey: "someValue") // 错误, 必须要继承自 NSObject
    
    // MARK: - kvc
    class KVCClass :NSObject{
       @objc var someValue: String = "123"
    }
    let kvc = KVCClass()
    kvc.someValue
    kvc.setValue("456", forKey: "someValue")
    kvc.someValue
    
    
    
    // MARK: - kvo
    
    class KVOClass:NSObject {
        @objc dynamic var someValue: String = "123"
        var someOtherValue: String = "abc"
    }
    
    class ObserverClass: NSObject {
        func observer() {
            let kvo = KVOClass()
            kvo.addObserver(self, forKeyPath: "someValue", options: .new, context: nil)
            kvo.addObserver(self, forKeyPath: "someOtherValue", options: .new, context: nil)
            kvo.someValue = "456"
            kvo.someOtherValue = "def"
            kvo.removeObserver(self, forKeyPath: "someValue")
            kvo.removeObserver(self, forKeyPath: "someOtherValue")
        }
        
        override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
           // print("\(keyPath!) change to \(change![.newKey] as! String)")
            debugPrint("\(keyPath!) change to \(change![.newKey] as! String)")
        }
    }
    ObserverClass().observer()
    debugPrint("123")
    
    
    var mutableArray = [1,2,3]
    for _ in mutableArray {
      mutableArray.removeLast()
    }
    debugPrint(mutableArray.description)
    
    

    demo 地址:
    https://gitee.com/johnson__save_admin/swift-kvokvcdemo

    相关文章

      网友评论

          本文标题:Swift KVO和KVC底层实现原理

          本文链接:https://www.haomeiwen.com/subject/qljflrtx.html