iOS:KVO

作者: 码小菜 | 来源:发表于2019-11-09 15:04 被阅读0次
    风景

    目录
    一,基本知识
    二,NSKVONotifying_Person
    三,NSKVONotifying_Person实例方法
    四,setAge:方法
    五,class,dealloc,_isKVOA
    六,手动发送通知
    七,使用进阶
    八,移除观察者

    一,基本知识

    1,概念

    KVOKey-Value-Observing的缩写,意思是键值观察,作用是监听对象某个属性的变化

    2,使用

    - (void)viewDidLoad {
        [super viewDidLoad];
        
        self.person = [Person new];
        self.person.age = 1;
        // 添加监听
        [self.person addObserver:self
                      forKeyPath:@"age"
                         options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
                         context:@"111"];
        self.person.age = 2;
    }
    
    // 监听到变化的回调
    - (void)observeValueForKeyPath:(NSString *)keyPath
                          ofObject:(id)object
                            change:(NSDictionary *)change
                           context:(void *)context {
        if (context == @"111") {
            NSLog(@"%@---%@---%@", object, keyPath, change);
        }
    }
    
    - (void)dealloc {
        // 移除监听
        [self.person removeObserver:self
                         forKeyPath:@"age"
                            context:@"111"];
    }
    
    // 打印
    <Person: 0x600003ae8ea0>---age---{
        kind = 1;
        new = 2;
        old = 1;
    }
    
    二,NSKVONotifying_Person

    self.person添加监听后,系统会自动生成Person的子类NSKVONotifying_Person,并让self.personisa指针指向它的类对象

    self.person = [Person new];
    NSLog(@"添加监听前:%@", object_getClass(self.person));
    [self.person addObserver:self
                  forKeyPath:@"age"
                     options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
                     context:@"111"];
    NSLog(@"添加监听后:%@", object_getClass(self.person));
    
    // 打印
    添加监听前:Person
    添加监听后:NSKVONotifying_Person
    
    添加监听前 添加监听后
    三,NSKVONotifying_Person实例方法
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        self.person = [Person new];
        [self logMethodNamesWithClass:[Person class]];
        [self.person addObserver:self
                      forKeyPath:@"age"
                         options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
                         context:@"111"];
        [self logMethodNamesWithClass:[Person class]];
    }
    
    // 打印类对象或元类对象中的方法名
    - (void)logMethodNamesWithClass:(Class)cls {
        unsigned int count;
        Method *methodList = class_copyMethodList(cls, &count);
        NSMutableString *methodNames = [NSMutableString string];
        for (int i = 0; i < count; i++) {
            Method method = methodList[i];
            SEL selector = method_getName(method);
            NSString *methodName = NSStringFromSelector(selector);
            [methodNames appendString:methodName];
            [methodNames appendString:@", "];
        }
        free(methodList);
        NSLog(@"%@---%@", cls, methodNames);
    }
    
    // 打印
    Person---setAge:, age,
    NSKVONotifying_Person---setAge:, class, dealloc, _isKVOA,
    
    实例方法
    四,setAge:方法

    1,在NSKVONotifying_Person类中的实现

    - (void)setAge:(NSInteger)age {
        [self willChangeValueForKey:@"age"];
        [super setAge:age];
        [self didChangeValueForKey:@"age"];
    }
    

    运行下面代码来验证一下

    @implementation Person
    - (void)setAge:(NSInteger)age {
        _age = age;
        NSLog(@"%@:setAge", object_getClass(self));
    }
    - (void)willChangeValueForKey:(NSString *)key {
        [super willChangeValueForKey:key];
        NSLog(@"%@:willChangeValueForKey", object_getClass(self));
    }
    - (void)didChangeValueForKey:(NSString *)key {
        [super didChangeValueForKey:key];
        NSLog(@"%@:didChangeValueForKey", object_getClass(self));
    }
    @end
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        self.person = [Person new];
        NSLog(@"添加监听前");
        self.person.age = 1;
        [self.person addObserver:self
                      forKeyPath:@"age"
                         options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
                         context:@"111"];
        NSLog(@"添加监听后");
        self.person.age = 2;
    }
    
    // 打印
    添加监听前
    Person:setAge
    添加监听后
    NSKVONotifying_Person:willChangeValueForKey
    NSKVONotifying_Person:setAge
    NSKVONotifying_Person:didChangeValueForKey
    

    2,didChangeValueForKey:方法

    - (void)didChangeValueForKey:(NSString *)key {
        NSLog(@"%@:didChangeValueForKey - begin", object_getClass(self));
        [super didChangeValueForKey:key];
        NSLog(@"%@:didChangeValueForKey - end", object_getClass(self));
    }
    
    - (void)observeValueForKeyPath:(NSString *)keyPath
                          ofObject:(id)object
                            change:(NSDictionary *)change
                           context:(void *)context {
        if (context == @"111") {
            NSLog(@"%@---%@---%@", object_getClass(object), keyPath, change);
        }
    }
    
    // 打印
    NSKVONotifying_Person:didChangeValueForKey - begin
    NSKVONotifying_Person---age---{
        kind = 1;
        new = 2;
        old = 1;
    }
    NSKVONotifying_Person:didChangeValueForKey - end
    

    由上可以看出是在[super didChangeValueForKey:key]中触发observeValueForKeyPath:方法的,所以在NSObject中此方法的实现如下

    - (void)didChangeValueForKey:(NSString *)key {
        // 参数是在添加监听时保存的
        [observer observeValueForKeyPath:keyPath
                                ofObject:self
                                  change:change
                                 context:context];
    }
    
    五,class,dealloc,_isKVOA

    1,class

    问题:self.person本质是NSKVONotifying_Person,为什么class方法返回Person
    答:因为NSKVONotifying_Person重写了class方法,返回了父类Person,这么做是为了隐藏底层实现细节,如果返回NSKVONotifying_Personclass方法的调用者会感到莫名其妙

    self.person = [Person new];
    [self.person addObserver:self
                  forKeyPath:@"age"
                     options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
                     context:@"111"];
    NSLog(@"%@", [self.person class]);
    NSLog(@"%@", object_getClass(self.person));
    
    // 打印
    Person
    NSKVONotifying_Person
    

    2,dealloc

    因为系统会自动生成NSKVONotifying_Person,所以需要重写dealloc方法,以便在销毁时清理系统产生的垃圾

    3,_isKVOA

    标识NSKVONotifying_PersonKVO产生的类

    - (BOOL)_isKVOA {
        return YES;
    }
    
    六,手动发送通知

    1,automaticallyNotifiesObserversForKey:方法是一个开关,如果返回YES,表示允许自动发送通知,修改属性值会收到回调;如果返回NO,表示不允许自动发送通知,修改属性值不会收到回调,必须手动发送通知才会收到回调;此方法默认返回YES
    2,手动发送通知必须同时调用willChangeValueForKey:方法和didChangeValueForKey:方法

    @implementation Person
    + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
        return NO;
    }
    @end
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        self.person = [Person new];
        self.person.age = 1;
        [self.person addObserver:self
                      forKeyPath:@"age"
                         options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
                         context:@"111"];
        // 手动通知
        [self.person willChangeValueForKey:@"age"];
        self.person.age = 2;
        [self.person didChangeValueForKey:@"age"];
    }
    
    // 打印
    <Person: 0x6000020d72f0>---age---{
        kind = 1;
        new = 2;
        old = 1;
    }
    
    七,使用进阶

    1,属性依赖

    一个对象的值取决于它内部所有属性的值,这种依赖关系可以通过keyPathsForValuesAffectingValueForKey:keyPathsForValuesAffecting<#DependentKey#>方法进行设置,一旦给该对象添加了监听,它内部任何属性的改变都会通知观察者

    // Dog
    @interface Dog : NSObject
    @property (nonatomic, copy) NSString *name;
    @property (nonatomic, assign) NSInteger age;
    @end
    
    @implementation Dog
    - (NSString *)description {
        return [NSString stringWithFormat:@"name: %@, age: %zd", _name, _age];
    }
    @end
    
    // Person
    @interface Person : NSObject
    @property (nonatomic, strong) Dog *dog;
    @end
    
    @implementation Person
    - (instancetype)init {
        if (self = [super init]) {
            _dog = [Dog new];
        }
        return self;
    }
    //+ (NSSet<NSString *> *)keyPathsForValuesAffectingValueForKey:(NSString *)key {
    //    if ([key isEqualToString:@"dog"]) {
    //        return [NSSet setWithObjects:@"_dog.name", @"_dog.age", nil];
    //    } else {
    //        return [super keyPathsForValuesAffectingValueForKey:key];
    //    }
    //}
    + (NSSet<NSString *> *)keyPathsForValuesAffectingDog {
        return [NSSet setWithObjects:@"_dog.name", @"_dog.age", nil];
    }
    @end
    
    // 使用Person
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        self.person = [Person new];
        self.person.dog.name = @"xiaoHuang";
        self.person.dog.age = 1;
        [self.person addObserver:self
                      forKeyPath:@"dog"
                         options:NSKeyValueObservingOptionNew
                         context:@"111"];
        self.person.dog.name = @"xiaoHei";
    }
    
    // 打印
    <Person: 0x6000004783d0>---dog---{
        kind = 1;
        new = "name: xiaoHei, age: 1";
    }
    

    2,监听容器对象中数据的变化

    不能直接拿容器对象进行操作,必须通过mutableArrayValueForKey:方法来获取容器对象,这样才能触发回调

    @interface Person : NSObject
    @property (nonatomic, strong) NSMutableArray *friends;
    @end
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        self.person = [Person new];
        self.person.friends = @[@"zhangSan"].mutableCopy;
        [self.person addObserver:self
                      forKeyPath:@"friends"
                         options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
                         context:@"111"];
    //    [self.person.friends addObject:@"liSi"];
        [[self.person mutableArrayValueForKey:@"friends"] addObject:@"liSi"];
    }
    
    // 打印
    <Person: 0x600002d30040>---friends---{
        indexes = "<_NSCachedIndexSet: 0x600002f669c0>[number of indexes: 1 (in 1 ranges), indexes: (1)]";
        kind = 2;
        new =     (
            liSi
        );
    }
    

    3,监听容器对象中元素(对象)的属性变化

    添加监听和移除监听用另外的方法

    @interface ViewController ()
    @property (nonatomic, strong) NSArray *pArray;
    @end
    
    @implementation ViewController
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        Person *p1 = [Person new];
        p1.age = 1;
        Person *p2 = [Person new];
        p2.age = 2;
        self.pArray = @[p1, p2];
    
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, self.pArray.count)];
        [self.pArray addObserver:self
              toObjectsAtIndexes:indexSet
                      forKeyPath:@"age"
                         options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
                         context:@"111"];
        p1.age = 3;
    }
    - (void)dealloc {
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, self.pArray.count)];
        [self.pArray removeObserver:self
               fromObjectsAtIndexes:indexSet
                         forKeyPath:@"age"
                            context:@"111"];
    }
    @end
    
    // 打印
    <Person: 0x6000036abc90>---age---{
        kind = 1;
        new = 3;
        old = 1;
    }
    
    八,移除观察者

    1,在观察者销毁时必须把它移除掉,否则在再次改变属性值时会crash

    // Person
    @implementation Person
    - (void)observeValueForKeyPath:(NSString *)keyPath
                          ofObject:(id)object
                            change:(NSDictionary *)change
                           context:(void *)context {
        if (context == @"111") {
            NSLog(@"%@---%@---%@", object, keyPath, change);
        }
    }
    - (void)dealloc {
        NSLog(@"Person dealloc");
    }
    @end
    
    // Dog
    @interface Dog : NSObject
    @property (nonatomic, assign) NSInteger age;
    @end
    
    // 使用
    self.person = [Person new];
    self.dog = [Dog new];
    self.dog.age = 1;
    [self.dog addObserver:self.person
               forKeyPath:@"age"
                  options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
                  context:@"111"];
    self.dog.age = 2;
    self.person = nil;
    self.dog.age = 3; // crash
    
    // 打印
    <Dog: 0x60000203c420>---age---{
        kind = 1;
        new = 2;
        old = 1;
    }
    Person dealloc
    

    2,在移除观察者时必须保证观察者没有销毁,否则会crash

    // 使用
    self.person = [Person new];
    self.dog = [Dog new];
    self.dog.age = 1;
    [self.dog addObserver:self.person
               forKeyPath:@"age"
                  options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
                  context:@"111"];
    self.dog.age = 2;
    self.person = nil;
    [self.dog removeObserver:self.person
                  forKeyPath:@"age"
                     context:@"111"];
    
    // 打印
    <Dog: 0x600001310830>---age---{
        kind = 1;
        new = 2;
        old = 1;
    }
    Person dealloc
    *** Terminating app due to uncaught exception 'NSRangeException', 
    reason: 'Cannot remove an observer <(null) 0x0> for the key path "age" from 
    <Dog 0x600001310830> because it is not registered as an observer.'
    

    3,移除观察者与添加观察者的次数必须保持一致,否则会crash

    // 使用
    self.person = [Person new];
    self.dog = [Dog new];
    self.dog.age = 1;
    BOOL isAdd = NO;
    if (isAdd) {
        [self.dog addObserver:self.person
                   forKeyPath:@"age"
                      options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
                      context:@"111"];
    }
    self.dog.age = 2;
    [self.dog removeObserver:self.person
                  forKeyPath:@"age"
                     context:@"111"];
    
    // 打印
    *** Terminating app due to uncaught exception 'NSRangeException', 
    reason: 'Cannot remove an observer <Person 0x600003173560> for the key path "age" from 
    <Dog 0x600003173570> because it is not registered as an observer.'
    

    相关文章

      网友评论

        本文标题:iOS:KVO

        本文链接:https://www.haomeiwen.com/subject/vcimbctx.html