iOS-KVO和KVC相关

KVO、KVC源码解读

2019-12-29  本文已影响0人  大冯宇宙

KVO

KVO是苹果Fundation框架提供的一套键值监听API,全称是Key-Value Observing,可以用于监听某个对象属性值的改变

使用

//定义类
@interface Person : NSObject
@property (assign, nonatomic) int age;
@property (assign, nonatomic) int height;
@end

//使用类
self.person = [[Person alloc] init];
// 给person对象添加KVO监听
NSLog(@"person添加KVO监听之前 - %@", object_getClass(self.person));
NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
[self.person addObserver:self forKeyPath:@"age" options:options context:@"123"];
[self.person addObserver:self forKeyPath:@"height" options:options context:@"456"];
NSLog(@"person添加KVO监听之后 - %@", object_getClass(self.person));

// 当监听对象的属性值发生改变时,就会调用
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    NSLog(@"监听到%@的%@属性值改变了 - %@ - %@", object, keyPath, change, context);
}
//当被监听的对象age、height发生变化的时候上边的回调就会打印,这里点击了屏幕
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    self.person.age = 20;
    self.person.height = 20;
}

原理

上文使用的代码,打印的类名
2019-12-29 21:08:23.555903+0800 test[11661:1118994] person添加KVO监听之前 - MJPerson
2019-12-29 21:08:23.556300+0800 test[11661:1118994] person添加KVO监听之后 - NSKVONotifying_MJPerson
比如person类
- (void)setAge:(int)age
{
    _NSSetIntValueAndNotify();
}

// 伪代码
void _NSSetIntValueAndNotify()
{
    [self willChangeValueForKey:@"age"];
    [super setAge:age];
    [self didChangeValueForKey:@"age"];
}

- (void)didChangeValueForKey:(NSString *)key
{
    // 通知监听器,某某属性值发生了改变
    [oberser observeValueForKeyPath:key ofObject:self change:nil context:nil];
}

证明

- (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);
}
//输出
2019-12-29 21:21:04.068859+0800 Interview01[11719:1127666] NSKVONotifying_Person setAge:, class, dealloc, _isKVOA,

面试题

KVC

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

使用方法

常见的API有

- (void)setValue:(id)value forKeyPath:(NSString *)keyPath;
- (void)setValue:(id)value forKey:(NSString *)key;
- (id)valueForKeyPath:(NSString *)keyPath;
- (id)valueForKey:(NSString *)key; 

setValue:forKey:的原理

valueForKey:的原理

KVC总结:

基于上边的原理图,我们通过代码去实际检验一下,可以看出程序是按照着上述的顺序去查找方法,所以我们可以认为

上一篇下一篇

猜你喜欢

热点阅读