#import <Foundation/Foundation.h>
#import "Person.h"
#import "Group.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
/*
KVC:Key Value Coding
*/
Person *p = [[Person alloc] init];
//点语法
//[p setName:@"wahaha"];p.name = @"wahaha";
/*KVC使用
在没有实现访问器方法时 那么kvc与点语法是一样的
key与成员变量同名
*/
//等同于getter setter
[p setValue:@"wahaha" forKey:@"name"];
id obj = [p valueForKey:@"name"];
NSLog(@"name is %@,%@",p.name,obj);
[p setValue:@"stduent" forKey:@"price"];
Group *g = [[[Group alloc] init] autorelease];
[g setValue:@"拉登" forKeyPath:@"person.name"];
NSLog(@"g.person name is %@",[g valueForKeyPath:@"person.name"]);
//或者:
NSLog(@"g.person name is %@",[g.person valueForKey:@"name"]);
//使用KVC同时设定多个键值
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"张三",@"name",[NSNumber numberWithInt:10],@"age" , nil];
[p setValuesForKeysWithDictionary:dic];
p.age = [NSNumber numberWithInt:1000];
NSLog(@"name %@ age %d",p.name,p.age);
id obj1 = [g valueForKey:@"friendArr"];
NSLog(@"obj1 is %@",obj1);
//获取好友列表中名字
id obj2 = [g.friendArr valueForKey:@"name"];
NSLog(@"obj2 is %@",obj2);
//5种简易运算符 @avg @sum @min @max @count
//10个好友的平均年龄
NSLog(@"avg.age is %@",[g.friendArr valueForKeyPath:@"@avg.age"]);
NSLog(@"max sge is %@",[g.friendArr valueForKeyPath:@"@max.age"]);
}
return 0;
}
{
NSString *_name;
int _age;
}
@property (nonatomic,assign) NSString *name;
@property (nonatomic,assign) int age;
-(void) setValue:(id)value forUndefinedKey:(NSString *)key;
Person.m中
@synthesize name = _name;
@synthesize age = _age;
- (void)dealloc
{
self.name = nil;
[super dealloc];
}
//这个方法在成员变量没有对应的key调用
-(void) setValue:(id)value forUndefinedKey:(NSString *)key
{
NSLog(@"value %@ key %@",value,key);
//试调用
NSLog(@"%s %d %s",__func__,__LINE__,__FILE__);
}
Group.h
#import <Foundation/Foundation.h>
#import "Person.h"
@interface Group : NSObject
{
Person *_person;
NSMutableArray *_friendArr;
}
@property (nonatomic,retain) Person *person;
@property (nonatomic,retain) NSMutableArray *friendArr;
@end
@synthesize person = _person;
@synthesize friendArr = _friendArr;
-(void)dealloc
{
self.person = nil;
[super dealloc];
}
- (id)init
{
self = [super init];
if (self) {
_person = [[Person alloc] init];
self.friendArr = [[[NSMutableArray alloc] init] autorelease];
for (int i = 0; i < 10; i++) {
Person *p = [[Person alloc] init];
p.name = [NSString stringWithFormat:@"zhangsan%2d",i];
p.age = i;
[_friendArr addObject:p];
[p release];
}
}
return self;
}