iOS面试专题

KVC 和 KVO详解

2018-08-23  本文已影响0人  苏东没有坡

KVC 详解

KVC : 键值编码(Key-Value Coding),它是一种通过key值访问类属性的机制,而不是通过setter/getter方法访问。

1. KVC 常用方法
/*
 取值
 */
// 通过key取值
- (id)valueForKey:(NSString *)key   
// 通过路径取值
- (nullable id)valueForKeyPath:(NSString *)keyPath  
// 找不到key抛出异常
- (nullable id)valueForUndefinedKey:(NSString *)key 

/* 
 修改
 */
// 对属性进行简单赋值
- (void)setValue:(nullable id)value forKey:(NSString *)key  
// 根据路径对属性赋值
- (void)setValue:(nullable id)value forKeyPath:(NSString *)keyPath 
// 找不到key的时候抛出异常
- (void)setValue:(nullable id)value forUndefinedKey:(NSString *)key
// 同时给多个属性进行赋值
- (void)setValuesForKeysWithDictionary:(NSDictionary<NSString *, id> *)keyedValues;

用代码进行简单的实验

//  Dog.m
@interface Dog ()
@property (nonatomic, copy) NSString *name;
@end

//  Woman.m
@interface Woman ()
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) Dog *dog;
@end

@implementation Woman
-  (instancetype)init 
    self = [super init];
    if (self) {
        Dog *dog = [[Dog alloc]init];
        self.dog = dog;
    }
    return self;
}
- (void)logName {
    NSLog(@"name:%@",self.name);
    NSLog(@"dogName:%@",[self.dog valueForKey:@"name"]);
}

// 调用
Woman *woman = [[Woman alloc]init];
[woman setValue:@"大丫" forKey:@"name"];
[woman setValue:@"二哈" forKeyPath:@"dog.name"];
[woman logName];

// 打印结果
name:大丫
dogName: 二哈

2 .KVC 原理
/*
 重写`+ (BOOL)accessInstanceVariablesDirectly`方法返回 NO
 */
//  Woman.m
@interface Woman (){
    NSInteger _age;
}

+ (BOOL)accessInstanceVariablesDirectly{
    return NO;
}
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
    NSLog(@"找不到key了");
}

// setValue:forKey:
 Woman *woman = [[Woman alloc]init];
 [woman setValue:@(18) forKey:@"age"];

// 打印结果
找不到key了

/* 
 找到了成员变量
 */
//  Woman.m
@interface Woman (){
    NSInteger _age; // 也可以是_age, _isAge, age, isAge
}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
    NSLog(@"找不到key了");
}

- (void)logAge {
    NSLog(@"age:%ld",_age);
}

// setValue:forKey:
 Woman *woman = [[Woman alloc]init];
 [woman setValue:@"18" forKey:@"age"];
 [woman logAge];

// 打印结果
 age:18

/* 
 没有成员变量,`+ (BOOL)accessInstanceVariablesDirectly`默认返回 YES
 */
//  Woman.m
@interface Woman (){
//    NSInteger _age;
}
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
    NSLog(@"找不到key了");
}

// setValue:forKey:
 Woman *woman = [[Woman alloc]init];
 [woman setValue:@"18" forKey:@"age"];

// 打印结果
找不到key了

KVO 详解

KVO:键值观察者 (Key-Value Observer): KVO 是观察者模式的一种实现,观察者A监听被观察者B的某个属性,当B的属性发生更改时,A就会收到通知,执行相应的方法。

1. KVO 相关方法
// 注册观察者
- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void *)context;
// 移除观察者 (带参数)
- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath context:(nullable void *)context API_AVAILABLE(macos(10.7), ios(5.0), watchos(2.0), tvos(9.0));
// 移除观察者 (不带参数)
- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath;

// 被观察者属性改变的回调方法 
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context ;

用代码进行简单实验

- (void)viewDidLoad {
    [super viewDidLoad];
    self.woman = [[Woman alloc]init];
    // 注册观察者,被观察的对象是woman的name属性,观察者为self
    [self.woman addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];
}

// 监听属性值发生改变后回调
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    NSLog(@"%@的%@改变了",object,keyPath);
}

// 点击屏幕的时候改变woman的name
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    self.woman.name = @"二丫";
}

打印结果
<Woman: 0x60000024cab0>的name改变了

2. KVO 实现原理

我们来看看 apple官方文档 对 KVO 具体实现的描述

Automatic key-value observing is implemented using a technique called isa-swizzling...
When an observer is registered for an attribute of an object the isa pointer of the observed object is modified, pointing to an intermediate class rather than at the true class.

KVO 使用了isa-swizzling 技术实现自动键值观察... 当观察者注册对象的属性时,观察对象的isa指针被修改,指向中间类而不是真正的类。

中间类,一语道破了KVO 的内在。

注册完观察者后,系统会做以下操作:

实际上apple为了隐藏自己偷偷摸摸建的这个类,他还偷偷重写了class方法,所以我们打印类名看到的依旧是Woman类。但是,如果我们创建一个NSKVONotifying_Woman类,编译的时候,系统就会自己露出马脚,告诉你KVO创建NSKVONotifying_Woman 类失败 。

KVO failed to allocate class pair for name NSKVONotifying_Woman, automatic key-value observing will not work for this class`

以上就是KVO内部的实现原理。

上一篇 下一篇

猜你喜欢

热点阅读