Swift3.0:KVO和Notification

2016-12-29  本文已影响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

上一篇下一篇

猜你喜欢

热点阅读