kvo原理:利用运行时,生成对象子类,并生成子类的对象,并替换原来的对象的isa指针(地址不发生变化,变化的是值),并且重写set方法。
//添加监听
[self addObserver:<#(nonnull NSObject *)#> forKeyPath:<#(nonnull NSString *)#> options:<#(NSKeyValueObservingOptions)#> context:<#(nullable void *)#>]
//实现方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
}
typedef NS_OPTIONS(NSUInteger, NSKeyValueObservingOptions) {
NSKeyValueObservingOptionNew ,//返回新值
NSKeyValueObservingOptionOld ,//返回老值
NSKeyValueObservingOptionInitial ,//再注册会发送一次通知,改变也会发送一次通知
NSKeyValueObservingOptionPrior //改变之前发送一次通知,改变之后也会发送一次通知
};
监听数组的变换
[self addObserver:self forKeyPath:@"dataArray" options:NSKeyValueObservingOptionNew context:nil]; [[self mutableArrayValueForKeyPath:@"dataArray"] addObject:@"one"];
多级路径的监听
+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key{
NSSet *keySet = [super keyPathsForValuesAffectingValueForKey:key];
if ([key isEqualToString:@"person"]) {
NSSet *set = [NSSet setWithObject:@"_person.age"];
keySet = [keySet setByAddingObjectsFromSet:set];
}
return keySet;
}
网友评论