iOS底层原理(二)KVO和KVC

KVO

KVO的全称是Key-Value Observing,俗称“键值监听”,可以用于监听某个对象属性值的改变

KVO的使用

可以通过addObserver: forKeyPath:方法对属性发起监听,然后通过observeValueForKeyPath: ofObject: change:方法中对应进行监听,见下面示例代码

// 示例代码
@interface Person : NSObject

@property (assign, nonatomic) int age;
@property (assign, nonatomic) int height;
@end

@implementation Person

@end

@interface ViewController ()

@property (strong, nonatomic) Person *person1;
@property (strong, nonatomic) Person *person2;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.person1 = [[Person alloc] init];
    self.person1.age = 1;
    
    self.person2 = [[Person alloc] init];
    self.person2.age = 2;
    
    // 打印添加监听之前person1和person2对应的isa指针指向的类型
    NSLog(@"person1添加KVO监听之前 - %@ %@",
          object_getClass(self.person1),
          object_getClass(self.person2)); 
    // 打印结果:Person Person
    
    // 打印添加监听之前person1和person2对应的setAge方法是否有改变
    NSLog(@"person1添加KVO监听之前 - %p %p",
          [self.person1 methodForSelector:@selector(setAge:)],
          [self.person2 methodForSelector:@selector(setAge:)]);
    // 0x10b60c4b0 0x10b60c4b0
          
    // 给person1对象添加KVO监听
    NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
    [self.person1 addObserver:self forKeyPath:@"age" options:options context:@"123"];
    
    // 打印添加监听之后person1和person2对应的isa指针指向的类型
    NSLog(@"person1添加KVO监听之后 - %@ %@",
          object_getClass(self.person1),
          object_getClass(self.person2)); 
	// 打印结果:NSKVONotifying_Person Person
	
	 // 打印添加监听之后person1和person2对应的setAge方法是否有改变
    NSLog(@"person1添加KVO监听之前 - %p %p",
          [self.person1 methodForSelector:@selector(setAge:)],
          [self.person2 methodForSelector:@selector(setAge:)]);
    // 0x7fff207b62b7 0x10b60c4b0
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    self.person1.age = 20;    
}

- (void)dealloc {
    [self.person1 removeObserver:self forKeyPath:@"age"];
}

// 当监听对象的属性值发生改变时,就会调用
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    NSLog(@"监听到%@的%@属性值改变了 - %@ - %@", object, keyPath, change, context);
}

@end

注意:监听的对象销毁之前要移除该监听removeObserver: forKeyPath:

KVO的实现本质

1.通过上面示例代码发现,函数在调用addObserver: forKeyPath:方法之后,person1的实例对象的isa指针指向了一个新的类型NSKVONotifying_Person,而没有添加监听的person2的isa指针还是指向了Person这个类型

2.我们发现通过object_getClass打印person1的类对象和元类对象都是新派生出来的NSKVONotifying_Person这个类型

NSLog(@"类对象 - %@ %@",
          object_getClass(self.person1), 
          object_getClass(self.person2)); 
// NSKVONotifying_Person Person

NSLog(@"元类对象 - %@ %@",
          object_getClass(object_getClass(self.person1)), 
          object_getClass(object_getClass(self.person2))); 
// NSKVONotifying_Person Person

3.我们发现通过object_getClass打印person1的superclass是Person这个类型,说明新派生出来的NSKVONotifying_Person是Person的子类

NSLog(@"父类 - %@ %@", 
		object_getClass(self.person1).superclass,
        object_getClass(self.person2).superclass);
        // Person NSObject

4.通过打印我们发现,person1调用的setAge方法的内存地址发生了改变,通过LLDB打印该地址的详细信息发现setAge方法的实现实际是Foundation框架中的_NSSetIntValueAndNotify这个函数

(lldb) p (IMP)0x7fff207b62b7
(IMP) $2 = 0x00007fff207b62b7 (Foundation`_NSSetIntValueAndNotify)
(lldb) p (IMP) 0x108801480
(IMP) $3 = 0x0000000108801480 (Interview01`-[Person setAge:] at Person.m:13)

5.我们手动创建这个派生类型NSKVONotifying_Person,并且在Person里面重写setAge:、willChangeValueForKey:、didChangeValueForKey:这三个方法,运行程序并观察调用情况

@interface NSKVONotifying_Person : Person

@end

@implementation NSKVONotifying_Person

@end


@interface Person : NSObject

@property (assign, nonatomic) int age;
@property (assign, nonatomic) int height;
@end

@implementation Person

- (void)setAge:(int)age
{
    _age = age;
    
    NSLog(@"setAge:");
}

- (void)willChangeValueForKey:(NSString *)key
{
    [super willChangeValueForKey:key];
    
    NSLog(@"willChangeValueForKey");
}

- (void)didChangeValueForKey:(NSString *)key
{
    NSLog(@"didChangeValueForKey - begin");
    
    [super didChangeValueForKey:key];
    
    NSLog(@"didChangeValueForKey - end");
}

@end

由此可见,当监听的属性发生改变,系统派生出的这个类NSKVONotifying_Person会对应的先后调用willChangeValueForKey:、setAge:、didChangeValueForKey:这三个方法,并在didChangeValueForKey:里调用观察者的observeValueForKeyPath: ofObject: change:来通知值属性值的变化

// 执行后打印
2021-01-19 13:42:02.071987+0800 Interview01[37119:19609444] willChangeValueForKey
2021-01-19 13:42:02.072192+0800 Interview01[37119:19609444] setAge:
2021-01-19 13:42:02.072332+0800 Interview01[37119:19609444] didChangeValueForKey - begin
2021-01-19 13:42:02.072662+0800 Interview01[37119:19609444] 监听到<Person: 0x6000036ac2c0>的age属性值改变了 - {
    kind = 1;
    new = 21;
    old = 1;
} - 123
2021-01-19 13:42:02.072817+0800 Interview01[37119:19609444] didChangeValueForKey - end

6.通过class方法打印person1的类发现还是Person这个类型,说明在派生出的这个类NSKVONotifying_Person内部重写了class方法,并返回的是Person这个类型。所以只能通过object_getClass才能获取到真实的类型

NSLog(@"%@ %@",
          [self.person1 class], 
          [self.person2 class]); 
// Person Person

NSLog(@"%@ %@",
          object_getClass(self.person1), 
          object_getClass(self.person2)); 
// NSKVONotifying_Person Person

7.通过Runtimeclass_copyMethodList函数查看NSKVONotifying_Person内部还动态生成了dealloc、_isKVOA这两个函数

- (void)printMethodNamesOfClass:(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];
        // 获得方法名
        NSString *methodName = NSStringFromSelector(method_getName(method));
        // 拼接方法名
        [methodNames appendString:methodName];
        [methodNames appendString:@", "];
    }
    
    // 释放
    free(methodList);
    
    // 打印方法名
    NSLog(@"%@ %@", cls, methodNames);
}

[self printMethodNamesOfClass:object_getClass(self.person1)];
[self printMethodNamesOfClass:object_getClass(self.person2)];

// 打印结果
2021-01-19 15:38:13.552990+0800 Interview01[41940:19730538] NSKVONotifying_MJPerson setAge:, class, dealloc, _isKVOA,
2021-01-19 15:38:13.553166+0800 Interview01[41940:19730538] MJPerson setAge:, age,

通过上面一系列操作可以汇总为:

  • 利用RuntimeAPI动态生成一个子类,并且让instance对象的isa指向这个全新的子类
  • 全新的子类会重写class这个函数,并返回父类类型- 当修改instance对象的属性时,会调用Foundation_NSSetXXXValueAndNotify函数- 调用willChangeValueForKey:- 调用父类原来的setter- 调用didChangeValueForKey:- 内部会触发监听器(Oberser)的监听方法 observeValueForKeyPath:ofObject:change:context:

iOS底层原理(二)KVO和KVC

KVC

KVC的全称是Key-Value Coding,俗称“键值编码”,可以通过一个key来访问某个属性

KVC的使用

可以通过setValue: forKeyPath:setValue: forKey:来给属性赋值,valueForKeyPath:valueForKey:来获取属性值。

setValue: forKeyPath:可以根据keyPath找到更深层次的属性来赋值,setValue: forKey:就只能找当前对象的属性,见下面示例代码

// 示例代码
@interface Cat : NSObject

@property (assign, nonatomic) int weight;
@end

@interface Person : NSObject

@property (assign, nonatomic) int age;
@property (strong, nonatomic) Cat *cat;
@end

@implementation Cat

@end

@implementation Person

@end

Person *person = [[Person alloc] init];
[person setValue:@10 forKey:@"age"];    
    
person.cat = [[Cat alloc] init];
[person setValue:@80 forKeyPath:@"cat.weight"];
        
// NSLog(@"%d, %d", person.age, person.cat.weight);
NSLog(@"%@", [person valueForKey:@"age"]);
        NSLog(@"%@", [person valueForKeyPath:@"cat.weight"]);
// 输出:10,80

注意:

  • 如果person.cat没有创建对象,那么setValue: forKeyPath:也不能给cat.weight属性赋值
  • 如果用setValue: forKey:方法来给cat.weight属性赋值,那么会抛出异常[<Person 0x100510ec0> setValue:forUndefinedKey:]

KVC的实现本质

setValue: forKey: 的实现本质

1.在Person里分别添加和注释setAge:、_setAge:两个方法,然后运行程序发现,内部会按顺序分别查找每个方法是否存在

@interface Person : NSObject

@end

@implementation Person

// 分别打开和注释下面两个方法

//- (void)setAge:(int)age
//{
//    NSLog(@"setAge: - %d", age);
//}

- (void)_setAge:(int)age
{
    NSLog(@"_setAge: - %d", age);
}

@end

2.注释掉上面两个方法后,重写accessInstanceVariablesDirectly方法并对应返回YES和NO,运行程序发现返回NO会抛出异常,说明不会再去查找是否有对应的属性。

accessInstanceVariablesDirectly默认的返回值就是YES

// 默认的返回值就是YES
+ (BOOL)accessInstanceVariablesDirectly
{
    //return YES;
    return NO;
}

3.最后我们在给Person对象分别添加和注释_age、_isAge、age、isAge这几个成员变量,运行程序发现,内部会按顺序分别查找每个成员变量是否存在,如果都没找到也会抛出异常

// 分别打开和注释下面的每个成员变量

@interface Person : NSObject
{
    @public
//    int age;
//    int isAge;
//    int _isAge;
    int _age;
}

@end

通过上面一系列操作可以汇总为:

iOS底层原理(二)KVO和KVC

valueForKey: 的实现本质

1.在Person里分别添加和注释getAge、age、isAge、_age几个方法,然后运行程序发现,内部会按顺序查找每个方法是否存在

@interface Person : NSObject

@end

@implementation MJPerson

// 分别打开和注释下面两个方法

- (int)getAge
{
    return 11;
}

//- (int)age
//{
//    return 12;
//}

//- (int)isAge
//{
//    return 13;
//}

//- (int)_age
//{
//    return 14;
//}

@end

2.同setValue: forKey:第二部操作一样,如果返回值为NO则抛出异常[<Person 0x105820160> valueForUndefinedKey:]

libc++abi.dylib: terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception ‘NSUnknownKeyException‘, reason: ‘[<Person 0x105820160> valueForUndefinedKey:]: this class is not key value coding-compliant for the key age.‘

3.同setValue: forKey:最后一步操作一样,只不过找到了对应的对应的成员变量直接取值,找不到也会抛出上面的异常

通过上面一系列操作也可以汇总为:

iOS底层原理(二)KVO和KVC

面试题

1.如何手动触发KVO?手动调用willChangeValueForKey:didChangeValueForKey:

2.直接修改成员变量会触发KVO么

不会触发KVO

3.通过KVC修改属性会触发KVO么?

会触发KVO

如示例代码所示,我们给Person添加一个成员变量age和一个只读属性weight,然后都是通过KVC的方式分别给它们赋值,发现都会触发KV0监听,并调用了willChangeValueForKeydidChangeValueForKey方法

// Person.h
@interface Person : NSObject
{
    @public
    int age;
}

@property (assign, nonatomic, readonly) int weight;
@end

// Person.m
@implementation Person

- (void)willChangeValueForKey:(NSString *)key
{
    [super willChangeValueForKey:key];
    
    NSLog(@"willChangeValueForKey");
}

- (void)didChangeValueForKey:(NSString *)key
{
    NSLog(@"didChangeValueForKey - begin");
    
    [super didChangeValueForKey:key];
    
    NSLog(@"didChangeValueForKey - end");
}
@end

// ViewController.m
@interface ViewController ()

@property (strong, nonatomic) Person *person;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.person = [[Person alloc] init];
            
    //添加KVO监听
    [self.person addObserver: self forKeyPath:@"age" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL];
    [self.person addObserver: self forKeyPath:@"weight" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL];
    
    [self.person setValue:@10 forKey:@"age"];
    [self.person setValue:@20 forKey:@"weight"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    NSLog(@"observeValueForKeyPath: %@",change);
}

- (void)dealloc {
    [self.person removeObserver:self forKeyPath:@"age"];
    [self.person removeObserver:self forKeyPath:@"weight"];
}
@end

// 输出结果
//willChangeValueForKey
//didChangeValueForKey - begin
//observeValueForKeyPath: {
//    kind = 1;
//    new = 10;
//    old = 0;
//}
//didChangeValueForKey - end
//
//
//willChangeValueForKey
//didChangeValueForKey - begin
//observeValueForKeyPath: {
//    kind = 1;
//    new = 20;
//    old = 0;
//}
//didChangeValueForKey - end

4.怎么通过KVO监听数组的元素变化?

我们可以通过数组的KVC方式添加元素,其底层会调用KVO触发监听器来监听数组元素变化

@interface ViewController ()

@property (nonatomic, strong) NSMutableArray *lines;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.lines = [NSMutableArray array];
    [self addObserver: self forKeyPath:@"lines" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL];
    [[self mutableArrayValueForKey:@"lines"] addObject:@"1"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    NSLog(@"observeValueForKeyPath: %@",change);
}

- (void)dealloc {
    [self removeObserver:self forKeyPath:@"lines"];
}
@end

// 打印:
observeValueForKeyPath: {
    indexes = "<_NSCachedIndexSet: 0x6000030afe60>[number of indexes: 1 (in 1 ranges), indexes: (0)]";
    kind = 2;
    new =     (
        1
    );
}

iOS底层原理(二)KVO和KVC

上一篇:Vue 3.x 中使用 Axios 请求远程Api接口数据


下一篇:b_tx_手机有电的最长时间(二分)