KVO:全称:key-value-observing,俗称“键值监听”,可以用于监听某个对象属性值的变化
内部实现(NSKVONotifying)
比如说监听一个对象(Person)的属性age,那么就会生成一个新的类(NSKVONotifying_Person)NSKVONotifying_Person是使用Runtime创建的一个新的类,是Person的子类。self.person.isa == NSKVONotifying_Person
那么在NSKVONotifying_Person类的age属性的set方法里面
-(void)setAge:(int)age{
NSSetIntValueAndNotify();
}
//伪代码
void _NSSetIntValueAndNotify(){
[self willChangeValueForKey:@"age"];
[super setAge:age]; //原来的setter实现
[self didChangeValueForKey:@"age"];
}
-(void)didChangeValueForKey:(NSString *)key{
//通知监听器,某某属性发生了改变
[observe observeValueForKeyPath:key ofObject:self Change:nil Context:nil];
}

补充:person对象监听age属性后
[self.person addObservier:self forKeyPath:@"age" options:options context:nil];
我们使用[self.person Class]得到的对象为Person;
我们使用[object_getClass(self.person)]得到的对象为NSKVONotifying_Person;

网友评论