// 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可以隨意修改一個(gè)對(duì)象的屬性或者成員變量(包括私有的顶滩,只讀的)
[person setValue:@"Bill" forKeyPath:@"name"];
[person setValue:@"male" forKeyPath:@"gender"];
[person setValue:@"180" forKeyPath:@"height"];
[person printHeight];
// 獲取數(shù)值
NSString *name = [person valueForKeyPath:@"name"];
2骑疆、key 和 keyPath 區(qū)別
/** forkeyPath包含forkey的功能
forKeyPath中可以里利用.運(yùn)算符敛滋,可以一層一層往下查找對(duì)象的屬性
使用forkey 報(bào)錯(cuò)找不到book.name這個(gè)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 = @"紅樓夢(mèng)";
NSArray *books = @[book1, book2, book3, book4];
/** 獲取所有的書名
原理:取出books數(shù)組中每一個(gè)元素name屬性值,放到一個(gè)新的數(shù)組中返回
**/
NSArray *names = [books valueForKeyPath:@"name"];
NSLog(@"%@",names);
(水滸傳,
三國演義,
西游記,
紅樓夢(mèng)
)
4矛缨、利用KVC將字典數(shù)據(jù)轉(zhuǎn)換為模型
setValuesForKeysWithDictionary:
//初始化數(shù)據(jù)
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