本文記錄 iOS 中 KVO(鍵值觀察)與 KVC(鍵值編碼)的學習成果,並附上可運行的完整範例。
Person 類別透過 addObserver:forKeyPath:options:context: 註冊觀察 BankAccount 的 openingBalance 屬性,並在 observeValueForKeyPath: 回呼中處理變化:
#import "Person.h"
@implementation Person
static void *OpeningBalance = (void *)&OpeningBalance;
- (id)init {
self = [super init];
if (self) {
bankAccount = [[BankAccount alloc] init];
}
return self;
}
- (void)registerAsObserver {
// 監聽 openingBalance 的變化
[bankAccount addObserver:self forKeyPath:@"openingBalance"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context:OpeningBalance];
}
- (void)unregisterObserver {
[bankAccount removeObserver:self forKeyPath:@"openingBalance"];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context {
if (context == OpeningBalance) {
NSString *v = [change objectForKey:NSKeyValueChangeNewKey];
NSLog(@"v is %@", v);
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
@end
被觀察的 BankAccount 以 timer 定時改變餘額。要注意:觸發 KVO 必須呼叫 setter 或手動 willChangeValueForKey/didChangeValueForKey,直接改寫成員變數並不會觸發通知:
- (void)balanceUpdate:(id)arg {
float f = self.openingBalance;
f += arc4random() % 100;
[self willChangeValueForKey:@"openingBalance"];
_openingBalance = f;
[self didChangeValueForKey:@"openingBalance"];
}
KVC 讓我們可用鍵(字串)存取屬性。PlayList 在 init 時建立 20 個 PlayItem,並示範多種 KVC 用法:
PlayList *pl = [[PlayList alloc] init]; [pl setValue:@"播放列表" forKey:@"name"]; // 設定單一鍵值 id v = [pl valueForKey:@"number"]; // 取值 [pl setValue:@"播放列表22" forKeyPath:@"currItem.name"]; // 鍵路徑設定 NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"200", @"number", @"測試", @"name", nil]; [pl setValuesForKeysWithDictionary:dict]; // 批次設定 id obj2 = [pl valueForKeyPath:@"itemList.name"]; // 取到更深層的值 // 集合運算子:求和、平均、最大、最小 NSLog(@"%@", [pl.itemList valueForKeyPath:@"@sum.price"]); NSLog(@"%@", [pl.itemList valueForKeyPath:@"@avg.price"]); NSLog(@"%@", [pl.itemList valueForKeyPath:@"@max.price"]); NSLog(@"%@", [pl.itemList valueForKeyPath:@"@min.price"]);
若存取不存在的 key,會觸發 setValue:forUndefinedKey:,可在此統一處理以避免崩潰。
對比可見,若不用 KVC,求總和得自己寫 for 迴圈遍歷;而用 @sum.price 一行即可完成。取深層屬性時,點語法無法直接取得,KVC 的鍵路徑卻輕鬆搞定——這正是 KVC 讓程式碼更簡潔有效之處。想深入了解者,可參考《深入淺出 Cocoa》中詳解 KVO 及其實現機理的文章。