概述
KVO官网
KVO
键值观察是一种机制,它允许对象被通知对其他对象的指定属性的更改.
KVO使用
- (void)viewDidLoad {
[super viewDidLoad];
// NSKeyValueObservingOptionNew = 0x01, //返回新值
//NSKeyValueObservingOptionOld = 0x02, //返回旧值
//NSKeyValueObservingOptionInitial //注册的时候就会发一次通知,改变的时候也会发通知
// NSKeyValueObservingOptionPrior //改变之前发一次,改变之后发一次
QHPerson *person = [[QHPerson alloc] init];
person.name = @"123";
[person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
_p = person;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
_p.name = @"qinhan";
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
NSLog(@"change:%@",change);
}
上面的是自动发送通知,kvc也提供了手动发送通知
//默认是自动
+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key
{
return NO;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[_p willChangeValueForKey:@"name"];
_p.name = @"qinhan";
[_p didChangeValueForKey:@"name"];
}
如果我们想见观察多个属性
QHPerson *person = [[QHPerson alloc] init];
person.name = @"123";
//[person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
[person addObserver:self forKeyPath:@"son" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
+(NSSet<NSString *> *)keyPathsForValuesAffectingValueForKey:(NSString *)key
{
NSSet *keypaths = [super keyPathsForValuesAffectingValueForKey:key];
if ([key isEqualToString:@"son"]) {
NSArray *arr = @[@"_son.nickName",@"_son.age"];
keypaths = [keypaths setByAddingObjectsFromArray:arr];
}
return keypaths;
}
这样我们可以观察person
属性的son
实例对象
kvo探索
1.我们分别定义了属性、成员变量,然后分别观察
[person addObserver:self forKeyPath:@"nickName" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
[person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
self.p.name =@"qinhan";
self.p->nickName = @"nickName";
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
NSLog(@"change:%@",change);
}
打印结果
2021-06-05 22:22:14.983537+0800 001---KVC基础使用[12792:12309284] change:{
kind = 1;
new = qinhan;
发送我们只监听到属性、没有监听到成员变量。可见kvo实际上时观察setter
方法
2.探索addObserver
在调用addObserver
前先打一个断点,
发现对象的指向的类发生了变化,通过下面的方法打印调用前和调用后类:
- (void)printClasses:(Class)cls{
// 注册类的总数
int count = objc_getClassList(NULL, 0);
// 创建一个数组, 其中包含给定对象
NSMutableArray *mArray = [NSMutableArray arrayWithObject:cls];
// 获取所有已注册的类
Class* classes = (Class*)malloc(sizeof(Class)*count);
objc_getClassList(classes, count);
for (int i = 0; i<count; i++) {
if (cls == class_getSuperclass(classes[i])) {
[mArray addObject:classes[i]];
}
}
free(classes);
NSLog(@"classes = %@", mArray);
}
结果如下图:
NSKVONotifying_QHPerson
实际上就时QHPerson
的子类
模拟KVO实现
注册自定义addobserver方法
[person qh_addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
自定义一个NSObject 分类
- (void)qh_addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void *)context
{
//自定义NSKVONotify_object 子类
NSString *oldClassName = NSStringFromClass(self.class);
NSString *newClassName = [@"QHKVO_" stringByAppendingString:oldClassName];
//创建一个类
Class myclass = objc_allocateClassPair(self.class, newClassName.UTF8String, 0);
//注册新类
objc_registerClassPair(myclass);
//动态修改 isa 指向中间类
object_setClass(self, myclass);
//给中间类重新添加setter方法
class_addMethod(myclass, @selector(setName:), (IMP)setName, "v@:@");
//将观察者绑定到对象上面
objc_setAssociatedObject(self, (__bridge const void *)@"objc", observer,OBJC_ASSOCIATION_ASSIGN );
}
void setName(id self,SEL _cmd ,NSString *newName){
struct objc_super person1 = {self,class_getSuperclass([self class])};
//调用父类的方法
objc_msgSendSuper(&person1, _cmd,newName);
NSLog(@"newName:%@",newName);
//拿到观察者
id observer = objc_getAssociatedObject(self, (__bridge const void *)@"objc");
//调用observer valueforkey 发送通知
objc_msgSend(observer, @selector(observeValueForKeyPath:ofObject:change:context:),@"name",self,@{@"name":newName});
}
总结KVO
- 验证是否存在setter方法
- 动态生成子类,需要重写class、setter方法
- 在子类的setter方法中向父类发消息
- 调用通知方法,把修改后的信息返回回去