ios KVC与KVO的探索研究

1. KVC

1.0 KVC的使用

  • LGStudent.h
#import 

NS_ASSUME_NONNULL_BEGIN

@interface LGStudent : NSObject
@property (nonatomic, copy)   NSString          *name;
@property (nonatomic, copy)   NSString          *subject;
@property (nonatomic, copy)   NSString          *nick;
@property (nonatomic, assign) int               age;
@property (nonatomic, assign) int               length;
@property (nonatomic, strong) NSMutableArray    *penArr;
@end

NS_ASSUME_NONNULL_END
  • LGPerson.h
#import 
#import "LGStudent.h"

NS_ASSUME_NONNULL_BEGIN

typedef struct {
    float x, y, z;
} ThreeFloats;

@interface LGPerson : NSObject{
   @public
   NSString *myName;
}

@property (nonatomic, copy)   NSString          *name;
@property (nonatomic, strong) NSArray           *array;
@property (nonatomic, strong) NSMutableArray    *mArray;
@property (nonatomic, assign) int age;
@property (nonatomic)         ThreeFloats       threeFloats;
@property (nonatomic, strong) LGStudent         *student;

@end

NS_ASSUME_NONNULL_END

我们在平时一般使用LGPerson *person = [[LGPerson alloc] init]; person.name = @"Cooci";这样的setter方法来对对象的某一个属性进行赋值,但是,我们也可以采用[person setValue:@"KC" forKey:@"name"];这样的Key-Value Coding (KVC)形式进行赋值。

    1. 集合类型
    person.array = @[@"1",@"2",@"3"];
    // 修改数组
    // 第一种:搞一个新的数组 - KVC 赋值就OK
    NSArray *array = [person valueForKey:@"array"];
    array = @[@"100",@"2",@"3"];
    [person setValue:array forKey:@"array"];
    NSLog(@"%@",[person valueForKey:@"array"]);
    // 第二种
    NSMutableArray *mArray = [person mutableArrayValueForKey:@"array"];
    mArray[0] = @"200";
    NSLog(@"%@",[person valueForKey:@"array"]);
    1. 结构体
    ThreeFloats floats = {1.,2.,3.};
    NSValue *value     = [NSValue valueWithBytes:&floats objCType:@encode(ThreeFloats)];
    [person setValue:value forKey:@"threeFloats"];
    NSValue *value1    = [person valueForKey:@"threeFloats"];
    NSLog(@"%@",value1);

    ThreeFloats th;
    [value1 getValue:&th];
    NSLog(@"%f-%f-%f",th.x,th.y,th.z);
    1. 通过keyPath访问
    LGStudent *student = [LGStudent alloc];
    student.subject    = @"大师班";
    person.student     = student;
    
    [person setValue:@"Swift" forKeyPath:@"student.subject"];
    NSLog(@"%@",[person valueForKeyPath:@"student.subject"]);
    1. 字典
    NSDictionary* dict = @{
                           @"name":@"Cooci",
                           @"nick":@"KC",
                           @"subject":@"iOS",
                           @"age":@18,
                           @"length":@180
                           };
    LGStudent *p = [[LGStudent alloc] init];
    // 字典转模型
    [p setValuesForKeysWithDictionary:dict];
    NSLog(@"%@",p);
    // 键数组转模型到字典
    NSArray *array = @[@"name",@"age"];
    NSDictionary *dic = [p dictionaryWithValuesForKeys:array];
    NSLog(@"%@",dic);

这些类型的使用在apple 官方文档中都有详细介绍。

1.2 KVC原理

ios KVC与KVO的探索研究_第1张图片
KVC.png

如图上可知, KVC的源码在 Foundation库内,而 Foundation库是未开源的,所以我们需要从 apple 官方文档去探索。

  • KVC设值流程
    官方文档:
    ios KVC与KVO的探索研究_第2张图片
    KVC - setter.png

    根据文档提示,第一步先要看是否实现了setKey方法或者_setKey方法。如果实现了setKey_setKey,则看accessInstanceVariablesDirectly方法中是否返回了YES,默认是返回YES的,如果你重写了此方法并返回NO,则代码会调用setValue:forUndefinedKey并发生异常。当accessInstanceVariablesDirectly方法返回了YES,则去找当前对象是否有key,_isKeykeyisKey,如果有,则设值完成,如果没有,则调用setValue:forUndefinedKey并发生异常。
    验证:
  • LGPerson.h
#import 
#import "LGStudent.h"

NS_ASSUME_NONNULL_BEGIN

@interface LGPerson : NSObject{
    @public

        NSString *_name;
        NSString *_isName;
        NSString *name;
        NSString *isName;
      
}

@end

NS_ASSUME_NONNULL_END
  • LGPerson.m
#import "LGPerson.h"

@implementation LGPerson

#pragma mark - 关闭或开启成员变量赋值
+ (BOOL)accessInstanceVariablesDirectly{
    return YES;
}

#pragma MARK:赋值 - setKey. 的流程分析
- (void)setName:(NSString *)name{
    NSLog(@"%s - %@",__func__,name);
}

- (void)_setName:(NSString *)name{
    NSLog(@"%s - %@",__func__,name);
}

- (void)setIsName:(NSString *)name{
    NSLog(@"%s - %@",__func__,name);
}

// 没有调用
- (void)_setIsName:(NSString *)name{
    NSLog(@"%s - %@",__func__,name);
}

@end
  • 调用
  LGPerson *person = [[LGPerson alloc] init];

  [person setValue:@"jeffery_zc" forKey:@"name"];

首先,按照官方文档,最先调用的是_Key,为了验证这个猜想,我们打印一下输出结果NSLog(@"%@-%@-%@-%@",person->_name,person->_isName,person->name,person->isName);发现只有person->_name有值,其他为null,于是,我们屏蔽LGPerson.h_name,再次输出打印结果NSLog(@"%@-%@-%@",person->_isName,person->name,person->isName);,发现person->_isName有值了,其他依旧是null。依次操作打印输出结果,得出结论与官方文档一致,设值流程为_key,_isKey,key,isKey

  • KVC取值流程
    官方文档:
    ios KVC与KVO的探索研究_第3张图片
    KVC取值01.png

ios KVC与KVO的探索研究_第4张图片
KVC取值02.png

根据官方文档,首先查询是否有 getKey,key,isKey,_key方法,如果有,先判断当前实例对象是否为集合类型,紧接着,判断 accessInstanceVariablesDirectly是否返回 YES,如果是,则寻找是否有 _key,_isKey,key,isKey的成员变量,如果有,判断是否为集合类型并做处理,如果没有,则调用 setValue:forUndefinedKey并发生异常。
验证:
LGPerson.m中的 setter验证方法屏蔽,添加如下代码:


#pragma MARK: 取值 - valueForKey 流程分析 - get, , is, or _,

- (NSString *)getName{
    return NSStringFromSelector(_cmd);
}

- (NSString *)name{
    return NSStringFromSelector(_cmd);
}

- (NSString *)isName{
    return NSStringFromSelector(_cmd);
}

- (NSString *)_name{
    return NSStringFromSelector(_cmd);
}
  • 验证getter方法取值的调用顺序
    NSLog(@"取值:%@",[person valueForKey:@"name"]);

第一次输出打印为getName,于是,我们屏蔽getName输出打印结果为name,依次屏蔽操作,得出官方文档第一步的结论,getter取值的调用顺序为getKey,key,isKey,_key

  • 验证成员变量取值顺序
    屏蔽LGPerson.msetter,getter方法,在调用代码中加入如下代码:
    person->_name = @"_name";
    person->_isName = @"_isName";
    person->name = @"name";
    person->isName = @"isName";

    NSLog(@"取值:%@",[person valueForKey:@"name"]);

第一次打印结果为_name,然后屏蔽成员变量_nameperson->_name = @"_name";,打印结果为_isName,依次操作,打印结果分别为_name,_isName,name,isName,正好与官方文档第四步一致。

2. KVO

2.1 KVO的使用

KVO(Key-value observing)是一种键值观察机制,它允许将其他对象的指定属性的更改通知给对象。我们通常使用KVO在控制器中观察某一对象的属性变化。

  • 注册通知:
- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void *)context;

observer:观察者,一般写self
keyPath:观察的键值,一般是对象的成员变量;
options:一种枚举值,比如新值旧值这些;
context:上下文,用来保存一些信息,contextvoid *类型,当只有一个观察者时,一般直接传null,当有多个观察者时,一般会定义多个void *类型的值用来区分。例:static void *PersonNickContext = &PersonNickContext;

  • KVO回调函数
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
   //处理事件
}
  • 移除观察者
- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath;

ios KVC与KVO的探索研究_第5张图片
移除观察者.png

根据官方文档描述,移除观察者是必须要进行的,如果你没有移除观察者,可能会报错 NSRangeException

  • 手动添加观察
    默认情况下,自动观察都是打开的,当我们需要手动进行观察某一个对象时,可以使用+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)theKey方法将自动观察关闭。
    ios KVC与KVO的探索研究_第6张图片
    关闭自动观察.png

    然后在观察的属性的赋值前添加willChangeValueForKey:方法,赋值后添加didChangeValueForKey :方法,这样,这一属性就变为手动观察了。
    ios KVC与KVO的探索研究_第7张图片
    手动观察.png

    官方文档还介绍了更多了的使用方法,这里我就不过多介绍了。
  • 路径处理
    假设我们需要检测当前的下载进度downloadProgress,而下载进度 = 已下载 / 总下载,所以我们可以利用集合将totalData总下载合并成一个downloadProgress,这样,我们就只需要观察downloadProgress就可以了。
// 下载进度 -- writtenData/totalData

+ (NSSet *)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 = 10;
    }
    if (self.totalData == 0) {
        self.totalData = 100;
    }
    return [[NSString alloc] initWithFormat:@"%f",1.0f*self.writtenData/self.totalData];
}
  • 数组观察
    self.person.dateArray = [NSMutableArray arrayWithCapacity:1];
    [self.person addObserver:self forKeyPath:@"dateArray" options:(NSKeyValueObservingOptionNew) context:NULL];

当我们给数组赋值时,不能直接进行addObject,而是需要valueForKey做一步转换才能观察到数组变化,代码如下:

    [[self.person mutableArrayValueForKey:@"dateArray"] addObject:@"1"];

2.2 KVO原理探究

官方文档:

ios KVC与KVO的探索研究_第8张图片
KVO 实现原理.png

根据文档提示,KVO是使用了 isa-swizzling的方法。在为某个对象注册观察者时,将这个对象的 isa指向了一个中间类,而不是原生的类,所以,我们不能依靠 isa确定类,而是应该通过 class去确定。

  • LGPerson.h
NS_ASSUME_NONNULL_BEGIN

@interface LGPerson : NSObject{
    @public
    NSString *name;
}
@property (nonatomic, copy) NSString *nickName;

@end

NS_ASSUME_NONNULL_END
  • LGPerson.m
#import "LGPerson.h"

@implementation LGPerson
- (void)setNickName:(NSString *)nickName{
    _nickName = nickName;
}
@end

我们分别对属性nickName和成员变量name添加观察者:

    self.person = [[LGPerson alloc] init];
    [self.person addObserver:self forKeyPath:@"nickName" options:(NSKeyValueObservingOptionNew) context:NULL];
    [self.person addObserver:self forKeyPath:@"name" options:(NSKeyValueObservingOptionNew) context:NULL];

当点击屏幕时对nickNamename进行赋值,然后进行观察:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"实际情况:%@-%@",self.person.nickName,self.person->name);
    self.person.nickName = @"KC";
    self.person->name   = @"jeffery";
}

#pragma mark - KVO回调
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    NSLog(@"%@",change);
}

ios KVC与KVO的探索研究_第9张图片
KVO-检测setter.png

通过输出发现,打印出来的 change只有 KC,也就是说只监测到了 nickName,而 nickNamename的区别则在于是否实现了 setter方法,也就是,KVO实际上是对 setter方法的监听。
由官方文档可知,在为对象注册了观察者时,改变了对象的 isa指针,并将对象的 isa指针指向了一个中间类,这时,我们不能通过 isa去获取类了,而是应该通过 class,此时,我们在注册观察者后设置了一个断点,打印出当前的类:
ios KVC与KVO的探索研究_第10张图片
KVO_中间类.png

通过打印可以看到,在添加了观察者之后,生成了 LGPerson的子类 NSKVONotifying_LGPerson,正如文档所说, self.person改变了 isa指针指向,接下来研究这个中间类实现了哪些方法:

#pragma mark - 遍历方法-ivar-property
- (void)printClassAllMethod:(Class)cls{
    unsigned int count = 0;
    Method *methodList = class_copyMethodList(cls, &count);
    for (int i = 0; i

在添加观察者后添加方法[self printClassAllMethod:objc_getClass("NSKVONotifying_LGPerson")];将这个中间类的实现方法打印出来:

ios KVC与KVO的探索研究_第11张图片
KVO中间类所实现的方法打印.png

通过打印可以看到中间类实现了 setNickName,class,dealloc,_isKVOA4个方法。既然 setNickName方法有打印,那就说明中间类重写了此方法。也就是说,我们将 nickName传给了中间类,但是发生改变的却是父类 LGPerson,所以可能在这里面的某个时间有传值操作。因为苹果建议通过 class来获取类,所以这里中间类的重写是获取原类的 classdealloc是释放方法, _isKVOA则是判断是否为KVO类。
ios KVC与KVO的探索研究_第12张图片
KVO移除观察者isa变化.png

当我们在 dealloc中移除观察者后,通过打印发现,· isa指针指向已经由中间类 NSKVONotifying_LGPerson只回了 LGPerson,那么 NSKVONotifying_LGPerson类是否会从内存中移除呢?
ios KVC与KVO的探索研究_第13张图片
KVO中间类存储.png
通过打印发现,当我们移除了观察者之后,生成的中间类会一直存储在内存当中。当我们再次进入观察时,就不需要重新开辟内存了。
总结
1.当对象在注册了观察者之后,其 isa指针会由原生类指向中间类;
2.KVO实际观察的是 setter方法;
3.移除观察者之后,实例对象的 isa指针会指回原生类;
4.中间类在创建之后,会一直存在于内存中。

你可能感兴趣的:(ios KVC与KVO的探索研究)