iOS底层原理 18 :KVO的原理

一、KVO的初体验

KVO的步骤:
  • 1.添加观察
  • 2.observe回调
  • 3.在合适位置更改观察属性的值
  • 4.在dealloc里移除观察
- (void)viewDidLoad {
    [super viewDidLoad];
    self.person  = [LGPerson new];
    [self.person addObserver:self forKeyPath:@"nick" options:NSKeyValueObservingOptionNew context:NULL];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    self.person.nick = [NSString stringWithFormat:@"%@+",self.person.nick];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    NSLog(@"%@",change);
}
- (void)dealloc{
    [self.person removeObserver:self forKeyPath:@"dateArray"];
}

二、KVO的其他用法

1、切换手动与自动
  • 自动开关 (默认)
+ (BOOL) automaticallyNotifiesObserversForKey:(NSString *)key{
    return YES;
}
  • 手动开关
+ (BOOL) automaticallyNotifiesObserversForKey:(NSString *)key{
    return NO;
}

- (void)setNick:(NSString *)nick{
    [self willChangeValueForKey:@"nick"];
    _nick = nick;
    [self didChangeValueForKey:@"nick"];
}
2、路径的处理
@implementation LGPerson
// 下载进度 -- writtenData/totalData
+ (NSSet<NSString *> *)keyPathsForValuesAffectingValueForKey:(NSString *)key{
    
    NSSet *keyPaths = [super keyPathsForValuesAffectingValueForKey:key];
    if ([key isEqualToString:@"downloadProgress"]) {
        NSArray *affectingKeys = @[@"totalData", @"writtenData"];
        keyPaths = [keyPaths setByAddingObjectsFromArray:affectingKeys];
    }
    return keyPaths;
}
- (NSString *)downloadProgress{
    if (self.writtenData == 0) {
        self.writtenData = 1.0;
    }
    if (self.totalData == 0) {
        self.totalData = 100;
    }
    return [[NSString alloc] initWithFormat:@"%f",1.0f*self.writtenData/self.totalData];
}
@end

@implementation LGViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.person  = [LGPerson new];
    // 4: 路径处理
    // 下载的进度 = 已下载 / 总下载
   [self.person addObserver:self forKeyPath:@"downloadProgress" options:(NSKeyValueObservingOptionNew) context:NULL];
}
@end
3、数组属性的监听
@interface LGPerson : NSObject
@property (nonatomic, strong) NSMutableArray *dateArray;
@end

@implementation LGViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.person  = [LGPerson new];
    // 1: 数组观察
    self.person.dateArray = [NSMutableArray arrayWithCapacity:1];
    [self.person addObserver:self forKeyPath:@"dateArray" options:(NSKeyValueObservingOptionNew) context:NULL];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    // KVC 集合 array
    [[self.person mutableArrayValueForKey:@"dateArray"] addObject:@"1"];
}

三、KVO的原理分析

首先我们断点到self.person = [[LGPerson alloc] init]后面,然后打印self.person的isaLFPerson


接着我们点击Step Next,然后程序执行完[self.person addObserver:self forKeyPath:@"nickName" options:(NSKeyValueObservingOptionNew) context:NULL],我们再次查看self.person的isa,却发现是NSKVONotifying_LGPerson

由此,我们猜测:KVO的底层改变了self.person的isa指向,并动态的创建了LGPerson的子类NSKVONotifying_LGPerson

接下来 我们添加如下代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    // KVO 底层原理
    self.person = [[LGPerson alloc] init];
   // 打印LGPerson的方法
    [self printClassAllMethod:[LGPerson class]];
    [self.person addObserver:self forKeyPath:@"nickName" options:(NSKeyValueObservingOptionNew) context:NULL];
    // 打印LGPerson的方法
    [self printClassAllMethod:[LGPerson class]];
    // 打印NSKVONotifying_LGPerson的方法
    Class cls = objc_getClass("NSKVONotifying_LGPerson");
    [self printClassAllMethod:cls];
}

// 打印cls的方法
- (void)printClassAllMethod:(Class)cls{
    unsigned int count = 0;
    NSLog(@"以下为%@的方法列表:",NSStringFromClass(cls));
    Method *methodList = class_copyMethodList(cls, &count);
    for (int i = 0; i<count; i++) {
        Method method = methodList[i];
        SEL sel = method_getName(method);
        IMP imp = class_getMethodImplementation(cls, sel);
        NSLog(@"%@-%p",NSStringFromSelector(sel),imp);
    }
    free(methodList);
}

打印的结果:


从打印的结果来看:
添加KVO,没有对LGPerson的进行添加方法的操作,而是对其子类动态的添加setNickName方法,也就是从写了父类的setNickName方法,动态的添加了+(Class)class, -(void)dealloc方法。

接下来我们在dealloc里面断点,在未执行remove操作前,self.person的isa指向NSKVONotifying_LGPerson


在执行remove操作后,self.person的isa指向LGPerson

综合上述,我们推测:

  • 动态的创建NSKVONotifying_LGPerson子类,并添加方法

    1. 添加class : class的指向是LGPerson

    2.添加setter(即: 重写setter方法)

  • 将对象的isa指向NSKVONotifying_LGPerson:object_setClass(self, newClass);

  • 将观察者信息保存在关联属性的NSKVO_AssiociateKey的可变数组中

  • 在重写的setter方法里面:

    • 将消息转发给父类,所以我们看到LGPerson里面的setNickName也会调用
    • 消息发送(将观察者作为消息的接受者, observeValueForKeyPath:ofObject:change:context: 作为 SEL)
  • 在移除监听时,将self.person的isa重新指向父类LGPerson

推荐阅读更多精彩内容