iOS开发之底层

iOS底层原理 18 :KVO的原理

2020-10-28  本文已影响0人  smooth_lgh

一、KVO的初体验

KVO的步骤:
- (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

综合上述,我们推测:

上一篇 下一篇

猜你喜欢

热点阅读