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將在該屬性值發生變化時執行- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context方法 [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