在iOS开发中经常会看到KVC和KVO这两个概念,比较可能混淆,特地区分一下
KVC(Key Value Coding)
1> 概述
KVC:Key Value Coding,键值编码,是一种间接访问实例变量的方法。
KVC 提供了一个使用字符串(Key)而不是访问器方法,去访问一个对象实例变量的机制。
2> KVC部分源码(头文件)
1 // NSKeyValueCoding.h
2 @interface NSObject(NSKeyValueCoding)
3
4 + (BOOL)accessInstanceVariablesDirectly;
5
6 - (nullable id)valueForKey:(NSString *)key;
7 - (void)setValue:(nullable id)value forKey:(NSString *)key;
8 - (BOOL)validateva lue:(inout id __nullable * __nonnull)ioValue forKey:(NSString *)inKey error:(out NSError **)outError;
9
10 - (NSMutableArray *)mutableArrayValueForKey:(NSString *)key;
11
12 - (NSMutableOrderedSet *)mutableOrderedSetValueForKey:(NSString *)key NS_AVAILABLE(10_7, 5_0);
13
14 - (NSMutableSet *)mutableSetValueForKey:(NSString *)key;
15
16 - (nullable id)valueForKeyPath:(NSString *)keyPath;
17 - (void)setValue:(nullable id)value forKeyPath:(NSString *)keyPath;
18 - (BOOL)validateva lue:(inout id __nullable * __nonnull)ioValue forKeyPath:(NSString *)inKeyPath error:(out NSError **)outError;
19 - (NSMutableArray *)mutableArrayValueForKeyPath:(NSString *)keyPath;
20 - (NSMutableOrderedSet *)mutableOrderedSetValueForKeyPath:(NSString *)keyPath NS_AVAILABLE(10_7, 5_0);
21 - (NSMutableSet *)mutableSetValueForKeyPath:(NSString *)keyPath;
22
23 - (nullable id)valueForUndefinedKey:(NSString *)key;
24 - (void)setValue:(nullable id)value forUndefinedKey:(NSString *)key;
25 - (void)setNilValueForKey:(NSString *)key;
26 - (NSDictionary<NSString *, id> *)dictionaryWithValuesForKeys:(NSArray<NSString *> *)keys;
27 - (void)setValuesForKeysWithDictionary:(NSDictionary<NSString *, id> *)keyedValues;
28
29 @end
30
31 @interface NSArray<ObjectType>(NSKeyValueCoding)
32
33 - (id)valueForKey:(NSString *)key;
34 - (void)setValue:(nullable id)value forKey:(NSString *)key;
35
36 @end
37
38 @interface NSDictionary<KeyType, ObjectType>(NSKeyValueCoding)
39
40 - (nullable ObjectType)valueForKey:(NSString *)key;
41
42 @end
43
44 @interface NSMutableDictionary<KeyType, ObjectType>(NSKeyValueCoding)
45
46 - (void)setValue:(nullable ObjectType)value forKey:(NSString *)key;
47
48 @end
49
50 @interface NSOrderedSet<ObjectType>(NSKeyValueCoding)
51
52 - (id)valueForKey:(NSString *)key NS_AVAILABLE(10_7, 5_0);
53 - (void)setValue:(nullable id)value forKey:(NSString *)key NS_AVAILABLE(10_7, 5_0);
54
55 @end
56
57 @interface NSSet<ObjectType>(NSKeyValueCoding)
58
59 - (id)valueForKey:(NSString *)key;
60 - (void)setValue:(nullable id)value forKey:(NSString *)key;
61
62 @end
可以看到这个类里面包含了对类NSObject、NSArray、NSDictionary、NSMutableDictionary、NSOrderedSet、NSSet的扩展,扩展方法基本上为
- (id)valueForKey:(NSString *)key;
- (void)setValue:(nullable id)value forKey:(NSString *)key;
也就是说,基本上Objective-C里所有的对象都支持KVC
操作,操作包含如上两类方法,动态读取和动态设值。
3> 通过KVC键值编码访问属性
① key值查找
1 [stu setValue:@"xiaoqiang" forKey:@"name"];
2 [stu setValue:@"boy" forKey:@"gender"];
3 [stu setValue:@24 forKey:@"age"];
4
5 NSLog(@"name = %@, gender = %@, age = %@", [stu valueForKey:@"name"], [stu valueForKey:@"gender"], [stu valu