KVC提供了以字符串的方式访问对象的数据,由于要解析字符串,所以性能有损耗
- (id) valueForKey: (NSString *) key; - (void) setValue: (id) value forKey: (NSString *) key; - (id) valueForKeyPath: (NSString *) keyPath; - (void) SetValue: (id) value forKeyPath: (NSString *) keyPath;
Objective-C在运行时使用元数据进入对象查找相关的信息,valueForKey:首先,查找以-key或isKey命名的getter方法,如果不存在getter方法,则会去查找_key或key命名的字段。
KVC提供了自动装箱的功能,以对值类型进行操作
// 199进行了装箱NSNumber [somePerson setValue: 199 forKey: @"height"]
// 拆箱
[somePerson valueForKey: @"height"]
获取集合
// 获取两只手的宽度集合 NSArray *array = [somePerson valueForKeyPath: @"hands.width"]
// array ( 15, 15.5)
进行运算
@count, @sum, @avg, @min, @max, @distinctUnionOfObjects
// 获取hand个数 [somePerson valueForKeyPath: @"hands.@count"] [somePerson valueForKeyPath: @"hands.@sum.width"] [somePerson valueForKeyPath: @"hands.@avg.width"] [somePerson valueForKeyPath: @"hands.@min.width"] [somePerson valueForKeyPath: @"hands.@max.width"] // 剔除穿着的同一品牌服饰 [somePerson valueForKeyPath: @"wears.@distinctUnionOfObjects.brand"]
批处理
- (id) dictionaryWithValuesForKeys: (NSArray *) array; - (void) setValuesForKeysWithDictionary: (NSDictionary *) dictionary; NSArray *keys = @[@"bob", @"smith"]; NSDictionary *dictionary = [somePerson dictionaryWithValuesForKeys: keys]; [somePerson setValuesForKeysWithDictionary: dictionary];