1. 程式人生 > >Object-C之KVC與KVO

Object-C之KVC與KVO

【一】KVC鍵值編碼
KVC全稱Key Value Coding
KVC由NSKeyValueCoding協議支援
用來給物件中的屬性進行賦值

幾個重要方法:
        FKBook *book = [[FKBook alloc] init]; 
        [book setValue:@"iOS" forKey:@"name"]; // 賦值
        NSString name = [book valueForKey:@"name"]; // 獲取值

        // 下面三個方法都是防止異常情況發生
        // 處理未定義的key
- (void)setValue:(id)value forUndefinedKey:(NSString *)key { } - (id)valueForUndefinedKey:(NSString *)key { return key; } // 處理nil - (void)setNilValueForKey:(NSString *)key { } // key路徑問題 // 其中item是物件,name是item物件中的屬性
[book setValue:@"iOS" forKeyPath:@"item.name"]; [book valueForKey:@"item.name"]; // 利用字典給物件賦值 [book setValuesForKeysWithDictionary:@{@"name":@"iOS"}];
KVC鍵值編碼的原理
1.會先找name屬性的setter和getter方法進行賦值或者獲取值
2.如果沒找到會尋找_name
3.如果沒找到會尋找name
3.如果都沒找到,會執行valueForUndefinedKey方法

【二】KVO鍵值監聽
KVO全稱Key Value Observing
由NSKeyValueObserving協議支援
用來解決模型中資料發生改變通知檢視元件重新整理問題

幾個重要的方法:
    // 增加監聽器
    - (void)setItem:(FKItem *)item
    {
        // self.item = item; 運用self.item賦值,會預設呼叫item的set方法,會造成迴圈呼叫錯誤
        self->_item = item;
        // 或者 _item = item;
        [self.item addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:@"hello world"];
        [self.item addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew context:nil];
    }

    // 模型中資料發生改變時,呼叫此方法
    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
        NSLog(@"keyPath = %@", keyPath);
        NSLog(@"object = %@", object);
        NSLog(@"change = %@", change);
        NSLog(@"context = %@", context);

        }

    // 當頁面銷燬時移除監聽器
    - (void)dealloc
    {
        [self.item removeObserver:self forKeyPath:@"name" context:@"hello world"];
        [self.item removeObserver:self forKeyPath:@"age"];
    }

KVO只有呼叫的setter和getter方法,才會觸發
KVO和iOS的訊息中心(NSNotificationCenter)有些相似
NSNotificationCenter由訊息中心統一發送通知,不限於監聽屬性的變化,使用比KVO更加靈活