Swift3.0 KVC & KVO

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)鍵字。

??

  1. 對(duì)要視察的對(duì)象的屬性加上dynamic關(guān)鍵字。
class KVODemo:NSObject{
    dynamic var demoDate = NSDate()
    func updateDate(){
        demoDate = NSDate()
    }
}
  1. 聲明一個(gè)全局的用來(lái)辨別是哪一個(gè)被視察屬性的變量。
    private var mycontext = 0

  2. 在要視察的類中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.
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 轉(zhuǎn)至元數(shù)據(jù)結(jié)尾創(chuàng)建: 董瀟偉,最新修改于: 十二月 23, 2016 轉(zhuǎn)至元數(shù)據(jù)起始第一章:isa和Class一....
    40c0490e5268閱讀 2,076評(píng)論 0 9
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,654評(píng)論 19 139
  • KVC(Key-value coding)鍵值編碼,單看這個(gè)名字可能不太好理解。其實(shí)翻譯一下就很簡(jiǎn)單了,就是指iO...
    朽木自雕也閱讀 1,702評(píng)論 6 1
  • 《ijs》速成開(kāi)發(fā)手冊(cè)3.0 官方用戶交流:iApp開(kāi)發(fā)交流(1) 239547050iApp開(kāi)發(fā)交流(2) 10...
    葉染柒丶閱讀 5,651評(píng)論 0 7
  • KVC(Key-value coding)鍵值編碼,單看這個(gè)名字可能不太好理解。其實(shí)翻譯一下就很簡(jiǎn)單了,就是指iO...
    黑暗中的孤影閱讀 50,265評(píng)論 74 441

友情鏈接更多精彩內(nèi)容