标签:
利用KVC可以随意修改一个对象的属性或者成员变量(并且私有的也可以修改)
示例代码:
示例一:
Person *p = [[Person alloc] init];
p.dog = [[Dog alloc] init];
// 输出结果都一样
p.dog.name = @"wangcai";
[p.dog setValue:@"laifu" forKey:@"name"];
[p.dog setValue:@"haha" forKey:@"name"];
[p.dog setValue:@"laifu" forKeyPath:@"name"];
[p.dog setValue:@"haha" forKeyPath:@"name"];
// 区别
// forKeyPath包含了forKey的功能, 以后使用forKeyPath
// forKeyPath中可以利用.运算符, 一层一层往下查找对象的属性
// [p setValue:@"laifu" forKey:@"dog.name"]; // 错误:没有dog.name的key
[p setValue:@"haha" forKeyPath:@"dog.name"];
NSLog(@"%@", p.dog.name);
示例二:
Person *p = [[Person alloc] init];
p.dog = [[Dog alloc] init];
p.dog.bone = [[Bone alloc] init];
p.dog.bone.type = @"骨头";
[p setValue:@"肉" forKeyPath:@"dog.bone.type"];
[p.dog setValue:@"肉" forKeyPath:@"bone.type"];
[p.dog.bone setValue:@"肉" forKeyPath:@"type"];
示例三: 用于获取值
Book *b1 = [[Book alloc] init];
b1.name = @"iOS";
b1.price = 10.5;
NSLog(@"%@", [b1 valueForKeyPath:@"name"]);
示例四:其他用法
Person *p = [[Person alloc] init];
Book *b1 = [[Book alloc] init];
b1.name = @"iOS";
b1.price = 10.5;
Book *b2 = [[Book alloc] init];
b2.name = @"Android";
b2.price = 15.5;
Book *b3 = [[Book alloc] init];
b3.name = @"PHP";
b3.price = 12.5;
Book *b4 = [[Book alloc] init];
b4.name = @"前端";
b4.price = 8;
p.books = @[b1, b2, b3, b4];
// 取出books数组中每一个元素的name属性值, 放到一个新的数组中返回
NSArray *names = [p valueForKeyPath:@"books.name"];
NSLog(@"%@", names);
// 利用KVC求和
double sum = [[p valueForKeyPath:@"books.@sum.price"] doubleValue];
// 利用KVC求平均
double average = [[p valueForKeyPath:@"books.@avg.price"] doubleValue];
标签:
原文地址:http://www.cnblogs.com/sjxjjx/p/4937436.html