KVC(KeyValueCoding) “键-值-编码”是一种可以直接通过字符串的名字(key)来访问类实例变量的机制。
KVC可以用来访问和设置实例变量的值。
设置方式:[self setValue:aName forKey:@"name"]
[self setValue:aName forKeyPath:@"person.name"]
访问方式: aString = [self valueForKey:@"name"]
aString = [self valueForKeyPath:@"person.name"]
1 主函数内容 2 Person *xiaoLi = [[Person alloc]init]; 3 // Book *book = [[Book alloc]init]; 4 // [book addMyObserver]; 5 6 [xiaoLi setBookName:@"《红楼梦》" andPrice:58]; 7 [xiaoLi setBookName:@"《三国演义》" andPrice:56.5]; 8 [xiaoLi setBookName:@"《水浒传》" andPrice:68.8]; 9 [xiaoLi setBookName:@"《西游记》" andPrice:75.2]; 10 11 NSArray *array = [xiaoLi valueForKeyPath:@"bookArray"]; 12 13 for (Book *book in array) 14 { 15 16 NSLog(@"%@ %@",[book valueForKey:@"bookName"],[book valueForKey:@"price"]); 17 } 18 19 20 21 #import <Foundation/Foundation.h> 22 #import "Book.h" 23 24 @interface Person : NSObject 25 { 26 NSString *name; 27 NSMutableArray *bookArray; 28 Book *aBook; 29 } 30 31 - (void)setBookName:(NSString *)bookName andPrice:(float)price; 32 33 @end 34 35 36 37 38 #import "Person.h" 39 #import "Book.h" 40 41 @implementation Person 42 43 - (void)setBookName:(NSString *)bookName andPrice:(float)price 44 { 45 // 如果bookArrar没有初始化,初始化 46 if (!bookArray) { 47 bookArray = [[NSMutableArray alloc]init]; 48 } 49 50 Book *book = [[Book alloc]init]; 51 52 // 开始监听书名的变化 53 [book addMyObserver]; 54 55 [self setValue:book forKey:@"aBook"]; 56 [self setValue:bookName forKeyPath:@"aBook.bookName"]; 57 58 // 把price封装成NSNumber数据赋值给bookName,读取bookName时会自动转为float 59 NSNumber *price1 = [NSNumber numberWithFloat:price]; 60 [self setValue:price1 forKeyPath:@"aBook.price"]; 61 62 // 把书装入数组 63 [bookArray addObject:aBook]; 64 65 } 66 67 @end 68 69 70 71 72 #import <Foundation/Foundation.h> 73 74 @interface Book : NSObject 75 76 { 77 NSString *bookName; 78 float price; 79 } 80 81 - (void)addMyObserver; 82 83 @end 84 85 86 87 88 #import "Book.h" 89 90 @implementation Book 91 92 - (void)addMyObserver 93 { 94 // 注册监听对象 95 [self addObserver:self forKeyPath:@"bookName" options:NSKeyValueObservingOptionNew context:nil]; 96 //observer 97 } 98 99 // 监听属性实例值的变化 100 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context 101 { 102 NSLog(@"bookName%@",change); 103 } 104 105 - (void)dealloc 106 { 107 // 移除监听 108 [self removeObserver:self forKeyPath:@"bookName"]; 109 [super dealloc]; 110 } 111 112 113 @end