试着用一种极为简单的例子来探索下KVC的用法,看完本文,相信会对大家的KVC的认识有一定的帮助.注意看代码.
KVC,即:Key-value coding,它是一种使用字符串标识符,间接访问对象属性的机制,它是很多技术的基础。
主要的方法就两个,setValue:forKey(setValuesForKeysWithDictionary),valueForKey.
主要用于Datamodel中的数据处理.使用该方法可以大大的简化代码,直接访问赋值model类中的属性的值.其中setvalue forkey 相当于setter方法.valueforkey相当于getter方法.以下为简单的使用实例.
创建一个Person类.也就是我们常用的dataModel类.
#import <Foundation/Foundation.h> #import "A.h" @interface Person : NSObject { NSString *_name; int _age; NSString *_sex; A *_a; } - (void)sayHi; @end以下为.m文件
#import "Person.h" @implementation Person - (void)dealloc { [_name release]; [_sex release]; [super dealloc]; } -(void)setValue:(id)value forUndefinedKey:(NSString *)key { // NSLog(@"key==%@",key); } - (void)sayHi { NSLog(@"name = %@ age = %d sex = %@ ",_name,_age,_sex); [_a ss]; } @end其中的setValue:forUndefindeKey:方法用来告诉系统使用setValue:forKey: 寻找不到key的时候,通知系统不必报错.
#import <Foundation/Foundation.h> @interface A : NSObject { NSString *_test; } - (void)ss; @end
#import "A.h" @implementation A - (void)dealloc { [_test release]; [super dealloc]; } - (void)ss { NSLog(@"+++%@",_test); } @end
NSString *file = [[NSBundle mainBundle] pathForResource:@"PersonData" ofType:@"plist"]; NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:file]; NSDictionary *d = [[dic objectForKey:@"C"]objectAtIndex:0]; Person *p = [[Person alloc] init]; [p setValuesForKeysWithDictionary:d]; [p setValue:@"LiSi" forKey:@"name"]; [p setValue:@"nan" forKey:@"sex"]; [p setValue:[NSNumber numberWithInt:20] forKey:@"age"]; A *aaa = [[A alloc] init]; //NSLog(@"%@",aaa); [p setValue:aaa forKey:@"a"]; [p setValue:@"haha" forKeyPath:@"a.test"]; NSLog(@"-----%@",[p valueForKey:@"sex"]); [p sayHi];