码迷,mamicode.com
首页 > 其他好文 > 详细

KVC的几种常用方法

时间:2016-04-01 20:25:21      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

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 allocinit];

[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 allocinit];

person.name = @"大锤";

person.gender = @"男";

NSLog(@"%@", person.name);

 

KVC方法:

Person *person = [[Person allocinit];

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 allocinit];

 

[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"]);

 

 

KVC的几种常用方法

标签:

原文地址:http://www.cnblogs.com/zhizunbao/p/5346065.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!