KVC_移动开发_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > 移动开发 > KVC

KVC

 2014/5/25 21:11:54  delegate  博客园  我要评论(0)
  • 摘要:KVC(keyvaluecoding)键值编码先定义两个类,person,dog1@interfaceDog:NSObject2@property(nonatomic,copy)NSString*name;3@end1#import<Foundation/Foundation.h>2@classDog;34@interfacePerson:NSObject5@property(nonatomic,copy)NSString*name;6@property(nonatomic
  • 标签:

KVC (key value coding)键值编码

先定义两个类,person,dog

1 @interface Dog : NSObject
2 @property (nonatomic,copy) NSString *name;
3 @end
 1 #import <Foundation/Foundation.h>
 2 @class Dog;
 3 
 4 @interface Person : NSObject
 5 @property (nonatomic,copy) NSString *name;
 6 @property (nonatomic,assign) int age;
 7 @property (nonatomic,copy) NSString *phone;
 8 @property (nonatomic,strong) Dog *dog;
 9 
10 @end
 1   //实例化两个person
 2         Person *p = [[Person alloc]init];
 3         Person *p1= [[Person alloc]init];
 4         //实例化dog
 5         Dog *d = [[Dog alloc] init];
 6         p.dog = d;
 7         
 8         NSArray *pArray = @[p,p1];
 9         
10 
11         // 1.给p.name赋值
12         [p setValue:@"Tom" forKey:@"name"];
13         
14         // 2.用字典给p的属性赋值,类的属性必须在字典中key存在,可以比字典中得key多,但是不能少。
15         [p setValuesForKeysWithDictionary:@{@"name":@"Jack",@"age":@10,@"phone":@"24234232"}];
16         
17         NSDictionary *dict = @{@"name":@"Cruise",@"age":@12,@"phone":@"123214wrew"};
18         
19         [p1 setValuesForKeysWithDictionary:dict];
20         
21        
22         // 3.按照键值路径赋值
23         [p setValue:@"fuck" forKeyPath:@"dog.dogName"];
24         
25         // 4.KVC按照键值路径取值时,如果对象不包含指定的键值,会自动进入对象内部,查找对象属性
26         NSArray *a = [pArray valueForKeyPath:@"name"];
27         
28         NSLog(@"%@",a);
29         
30         NSLog(@"%@ ,name= %@,age = %d,phone = %@,dogname = %@",p,p.name,p.age,p.phone,p.dog.dogName);

输出结果:2014-05-25 19:49:26.634 xcode 小技巧- 自定义代码块[832:303] (
    Jack,
    Cruise
)
2014-05-25 19:49:26.641 xcode 小技巧- 自定义代码块[832:303] <Person: 0x100202d50> ,name= Jack,age = 10,phone = 24234232,dogname = fuck

  • 相关文章
发表评论
用户名: 匿名