KVC 簡介設值的一個工具,對於指向id的對象,像其內存存取值。這有點像java的反射;
存在如下一個對象,已知其屬性name,可取值:
id p=[[Person alloc] init]; NSString *name=[p valueForKey:@"name"];
Book *book1=[[Book alloc] init]; book1.name=@"effctive c++"; Book *book2=[[Book alloc] init]; book2.name=@" more effctive c++"; Book *book3=[[Book alloc] init]; book3.name=@" most effctive c++"; NSArray *arr=@[book1,book2,book3]; NSLog(@"%@",[arr valueForKey:@"name"]);
KVO指的是設值過程中對其監聽的過程,以實現對業務邏輯的校驗
//創建一個被監視的對象 Book *book1=[[Book alloc] init]; //設置監聽對象 BookObserve *observe=[[BookObserve alloc] init]; //對其存值的監聽-這種方法用完後不需要移除監聽器 [observe observeValueForKeyPath:@"name" ofObject:book1 change:nil context:@"sadsada"]; //對其存值的監聽-02 [book1 addObserver:observe forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil]; book1.name=@" most effctive c++"; NSLog(@"%@",book1.name); //取消對其存值的監聽-02 [book1 removeObserver:observe forKeyPath:@"name"];
只要在.m文件中實現如下方法即可監聽:
#pragma mark keyPath:對象屬性 object:對象 change:存取值保存的字典 -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { }