swift5中的kvc监听无效

烂漫一生 提交于 2020-10-02 16:10:41

如题,记录下swift中监听自定义属性失效的问题

极简单的例子

import UIKit

class HZJViewController: UIViewController {

    var name:String = "one"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        self.addObserver(self, forKeyPath: "name", options: [.old,.new], context: nil)
    }
    
    deinit {
        self.removeObserver(self, forKeyPath: "name")
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "name" {
            print(change)
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.name = "two"
    }
}

处理方法:添加@objcdynamic

@objc dynamic var name:String = "one"

至于原因,各位还是百度吧,不想copy。。[旺柴]

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!