Objective-C KVC总结

大纲

  • setValue:forKeysetValue:forKeyPath
  • 赋值流程解析
  • 取值流程解析

1. setValue:forKey 和 setValue:forKeyPath

@interface CWObject: NSObject{}
@property (nonatomic, assign) NSInteger count;
@end

我们可以通过KVC给count赋值

- (void)viewDidLoad {
    [super viewDidLoad];
    
    CWObject *obj = [[CWObject alloc] init];
    
    [obj setValue:@1 forKey:@"count"];
    NSLog(@"%ld", obj.count);
    
    [obj setValue:@2 forKeyPath:@"count"];
    NSLog(@"%ld", obj.count);
}

既然都能赋值,那么key和keyPath的区别是什么呢?直接看演示代码

@interface Cat: NSObject{}
@property (nonatomic, assign) CGFloat weight;
@end

@interface CWObject: NSObject{}
@property (nonatomic, assign) NSInteger count;
@end

keyPath可以多级关联,但是key不可以,代码如下

- (void)viewDidLoad {
    [super viewDidLoad];
    
    CWObject *obj = [[CWObject alloc] init];
    obj.cat = [[Cat alloc] init];
    
    [obj.cat setValue:@1.0 forKey:@"weight"];
    NSLog(@"%lf", obj.cat.weight);
    
    [obj setValue:@2.0 forKeyPath:@"cat.weight"];
    NSLog(@"%lf", obj.cat.weight);
}

当赋值或者取值时,key不存在会crash,为了防止可以重写如下两个方法:

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
    NSLog(@"setValueForKey: [%@] undefined!", key);
}

- (id)valueForUndefinedKey:(NSString *)key {
    NSLog(@"getValueForKey: [%@] undefined!", key);
    return nil;
}

2. 赋值流程图

赋值流程图

3. 取值流程图

取值流程图
  • 关于取值流程图,其实里面还有countOf<key>objectIn<key>AtIndex<key>AtIndexesenumeratorOf<key>memberOf<key>这一套流程,在图中没有画出来,因为平时基本用不上,后面可能会考虑加上。

流程图这里就不一一贴验证代码了,有兴趣的可以自行验证。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。