iOS:KVO原理分析

目录
一,基本知识
二,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.'
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,723评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,003评论 3 391
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,512评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,825评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,874评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,841评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,812评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,582评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,033评论 1 308
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,309评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,450评论 1 345
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,158评论 5 341
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,789评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,409评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,609评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,440评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,357评论 2 352