KVC
key-value coding。
- 是一種間接訪問(wèn)對(duì)象的機(jī)制。
- key的值就是屬性名稱的字符串,返回的value是任意類型,需要自己轉(zhuǎn)化為需要的類型。
- KVC主要就是兩個(gè)方法。
通過(guò)key設(shè)置對(duì)應(yīng)的屬性。
通過(guò)key設(shè)置對(duì)應(yīng)的屬性。
??
class KVCDemo:NSObject{
var data = "hello world"
}
var instance = KVCDemo()
var value = instance.value(forKey: "data") as! String
instance.setValue("hello hhy",forKey:"data")
print(instance.data)//
KVO
key-value observing。
- 建立在KVC之上的的機(jī)制。
- 主要功能是檢測(cè)對(duì)象屬性的變化。
- 這是一個(gè)完善的機(jī)制,不需要用戶自己設(shè)計(jì)復(fù)雜的視察者模式。
- 對(duì)需要視察的屬性要在前面加上dynamic關(guān)鍵字。
??
- 對(duì)要視察的對(duì)象的屬性加上dynamic關(guān)鍵字。
class KVODemo:NSObject{
dynamic var demoDate = NSDate()
func updateDate(){
demoDate = NSDate()
}
}
聲明一個(gè)全局的用來(lái)辨別是哪一個(gè)被視察屬性的變量。
private var mycontext = 0在要視察的類中
addObserver,在析構(gòu)中removeObserver,重寫(xiě)observeValue。
data.addObserver(self, forKeyPath: "demoDate", options: .new, context: &mycontext)
deinit {
data.removeObserver(self,forKeyPath:"demoDate")
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
print("\(context!)============\(mycontext)")
if(context == &mycontext) {
print("Changed to:(change[NSKeyValueChangeNewKey]!)")
}
}
@IBAction func button(_ sender: AnyObject) {
data.updateDate()
}
--
完整代碼
import Foundation
class KVODemo:NSObject{
dynamic var demoDate = NSDate()
func updateDate(){
demoDate = NSDate()
}
}
import UIKit
private var mycontext = 0
class ViewController: UIViewController {
var data = KVODemo()
override func viewDidLoad() {
super.viewDidLoad()
//1.注冊(cè)監(jiān)聽(tīng)對(duì)象
data.addObserver(self, forKeyPath: "demoDate", options: .new, context: &mycontext)
//forKeyPath: "demoDate" - 需要監(jiān)聽(tīng)的屬性
//options: .new - 指返回的字典包含新值
//options: .old - 指返回的字典包含舊值。
//context: &mycontext -context方便傳輸你需要的數(shù)據(jù),它是個(gè)指針類型
}
deinit {
data.removeObserver(self,forKeyPath:"demoDate")
}
//2. 實(shí)現(xiàn)監(jiān)聽(tīng)方法
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
print("\(context!)============\(mycontext)")
if(context == &mycontext) {
print("Changed to:(change[NSKeyValueChangeNewKey]!)")
}
}
@IBAction func button(_ sender: AnyObject) {
data.updateDate()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}