KVC简单使用

2016-06-24  本文已影响0人  最远的地方00
// Person模型
@interface Person : NSObject
{
    @private
    double _height;
}
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, copy, readonly) NSString *gender;
@prpperty (nonatomic, strong) Book *book;
- (void)printHeight;

.m
- (void)printHeight {
    NSLog(@"Height is %f",_height);
}
// Book模型
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) double price;

1、KVC使用

// 使用KVC可以随意修改一个对象的属性或者成员变量(包括私有的,只读的)
[person setValue:@"Bill" forKeyPath:@"name"];
[person setValue:@"male" forKeyPath:@"gender"];
[person setValue:@"180" forKeyPath:@"height"];
[person printHeight];

 // 获取数值
 NSString *name = [person valueForKeyPath:@"name"];

2、key 和 keyPath 区别

/** forkeyPath包含forkey的功能
    forKeyPath中可以里利用.运算符,可以一层一层往下查找对象的属性
    使用forkey 报错找不到book.name这个key
*/
// [person setValue:@"Harry Potter" forKey:@"book.name"];
[person setValue:@"Harry Potter" forKeyPath:@"book.name"];

3、获取所有同属性的值

// 获取所有同属性的值
Book *book1 = [[Book alloc] init];
book1.name = @"水浒传";

Book *book2 = [[Book alloc] init];
book2.name = @"三国演义";

Book *book3 = [[Book alloc] init];
book3.name = @"西游记";

Book *book4 = [[Book alloc] init];
book4.name = @"红楼梦";

NSArray *books = @[book1, book2, book3, book4];

/** 获取所有的书名
    原理:取出books数组中每一个元素name属性值,放到一个新的数组中返回
 **/
NSArray *names = [books valueForKeyPath:@"name"];
NSLog(@"%@",names);

(水浒传,
三国演义,
西游记,
红楼梦
)

4、利用KVC将字典数据转换为模型
setValuesForKeysWithDictionary:

//初始化数据
NSDictionary *dic  = [NSDictionary dictionaryWithObjectsAndKeys:@"james",@"name",@"male", @"gender",@"18",@"age", nil];

Person *person = [[Person alloc] init];
[person setValuesForKeysWithDictionary:dic];
NSLog(@"name:%@,gender:%@,age:%ld",person.name,person.gender,person.age);

//name:james,gender:male,age:18
上一篇下一篇

猜你喜欢

热点阅读