KVC:Key-Value Coding(鍵值編碼)
KVO:Key-Value Observing(鍵值觀察)
下面透過一個簡單的範例來說明兩者的用法。
Person.m:
@interface Person : NSObject{
// 該存取修飾符用於說明:即使是私有成員變數,也能透過 KVC 方式存取與賦值
@private
NSString *_name;
}
@end
@implementation Person
@end
PersonObserve.m:
@interface PersonObserve : NSObject
@end
@implementation PersonObserve
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
Person *p = (Person *)object;
// 使用 KVC 方式取得 keyPath 對應的成員變數值
NSLog(@"%@", [p valueForKey:keyPath]);
}
@end
main.m:
int main(int argc, const char * argv[]) {
// 建立觀察者物件
PersonObserve *po = [[PersonObserve alloc] init];
Person *p = [[Person alloc] init];
// 使用 KVO 為成員變數「name」的屬性值變化註冊觀察者 po
// 當該屬性值改變時,po 會執行 observeValueForKeyPath:... 方法
[p addObserver:po forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];
// 透過 KVC 設定成員變數「name」的值,進而觸發觀察者的回呼方法
[p setValue:@"yangys" forKey:@"name"];
// 移除對私有成員變數「name」的觀察
[p removeObserver:po forKeyPath:@"name"];
return 0;
}
執行結果:
2015-03-02 20:57:52.487 KVC&KOC[843:24874] yangys Program ended with exit code: 0