标签:
KVC的使用1:
以Person为例:
@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@end
属性的方法:
Person *person = [[Person alloc] init];
person.name = @"大锤";
NSLog(@"%@", person.name);
KVC方法:
Person *person = [[Person alloc] init];
[person setValue:@"盖聂" forKey:@"name"];
NSLog(@"%@", [person valueForKey:@"name"]);
KVC的使用2:
还是以Person为例:
@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *gender;
@end
属性方法:
Person *person = [[Person alloc] init];
person.name = @"大锤";
person.gender = @"男";
NSLog(@"%@", person.name);
KVC方法:
Person *person = [[Person alloc] init];
NSDictionary *dict = @{@"name" : @"哈哈哈", @"gender" : @"man"};
[person setValuesForKeysWithDictionary:dict];
NSLog(@"%@, %@", [person valueForKey:@"name"], [person valueForKey:@"gender"]);
KVC的使用3:
以Person和Teacher为例:
@class Teacher;
@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *gender;
@property (nonatomic, retain) Teacher *tea;
@end
@interface Teacher : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *sex;
@property (nonatomic, assign) NSInteger age;
@end
属性的方法:
Person *p = [[Person alloc] init];
Teacher *t = [[Teacher alloc] init];
p.tea = t;
t.name = @"哈哈哈";
NSLog(@"%@", p.tea.name);
KVC的方法:
Person *person = [[Person alloc] init];
Teacher *t = [[Teacher alloc] init];
[person setValue:t forKey:@"teacher"];
[person setValue:@"卫庄" forKeyPath:@"tea.name"];
NSLog(@"%@", [person valueForKeyPath:@"tea.name"]);
其实如果我们Person类重写init的话:
- (instancetype)init {
if (self = [super init]) {
_tea = [[Teacher alloc] init];
}
return self;
}
就可以直接像下面这么写了:
Person *person = [[Person alloc] init];
[person setValue:@"卫庄" forKeyPath:@"tea.name"];
NSLog(@"%@", [person valueForKeyPath:@"tea.name"]);
标签:
原文地址:http://www.cnblogs.com/zhizunbao/p/5346065.html