JHHK

欢迎来到我的个人网站
行者常至 为者常成

KVC

目录

基本使用

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

创建一个Person和Cat类
Person.h

NS_ASSUME_NONNULL_BEGIN
@interface Cat:NSObject
@property (nonatomic, assign) float weight;
@end

@interface Person : NSObject;
@property (nonatomic, strong) Cat * cat;
@property (nonatomic, assign) int age;
@end
NS_ASSUME_NONNULL_END

Person.m

#import "Person.h"
@implementation Cat

@end

@implementation Person

@end

使用案例

- (void)viewDidLoad {
    [super viewDidLoad];
    
    Person * person = [[Person alloc] init];
    person.cat = [[Cat alloc] init];
    
    [person addObserver:self
             forKeyPath:@"age"
                options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
                context:@"123"];
    
    
    [person setValue:@18 forKey:@"age"];
    [person setValue:@10 forKeyPath:@"cat.weight"];
    
    NSLog(@"person.age=%@",[person valueForKey:@"age"]);
    NSLog(@"person.cat.weight=%@",[person valueForKeyPath:@"cat.weight"]);
}


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

打印日志为

iOSTest[540:67244] object=<Person: 0x2801bbd00>
iOSTest[540:67244] change={
    kind = 1;
    new = 18;
    old = 0;
}
iOSTest[540:67244] context=123
iOSTest[540:67244] person.age=18
iOSTest[540:67244] person.cat.weight=10

分析

一、setValue:forKey:的原理

img

+(BOOL)accessInstanceVariablesDirectly;该方法的默认返回值是YES

二、valueForKey:的原理

img


行者常至,为者常成!





R
Valine - A simple comment system based on Leancloud.