美文网首页
Swift3.0:KVO和Notification

Swift3.0:KVO和Notification

作者: 学游泳的小黑 | 来源:发表于2016-12-29 09:27 被阅读91次

    (基于Swift3.0语法)都是挺简单的直接对比吧

    1、KVO(键值观察)

    @IBOutlet weak var kvoLab: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        self.kvoLab.addObserver(self, forKeyPath: "text", options: NSKeyValueObservingOptions.new, context: nil)
    }
    
    @IBAction func action_ClickButton(_ sender: UIButton) {
        self.kvoLab.text = "点击了\(sender.tag)按钮"
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        print("keyPath = \(keyPath)")
        print("object = \(object)")
        print("context = \((object! as! UILabel).text!)")
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    2、NSNotification(通知)

    let notification = NSNotification.Name(rawValue: "notify")
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        NotificationCenter.default.addObserver(self, selector: #selector(textChange(notification:)), name: self.notification, object: nil)
    }
    
    @IBAction func action_ClickButton(_ sender: UIButton) {
        NotificationCenter.default.post(name: self.notification, object: nil, userInfo: ["text":sender.tag])
    }
    
    func textChange(notification: NSNotification) {
        print("notification = \(notification)")
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    项目地址:KVO&Notification

    相关文章

      网友评论

          本文标题:Swift3.0:KVO和Notification

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