假设有对象如下:
@interface Person : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) NSInteger age;
@end
实例化如下:
Person *p1 = [[Person alloc] init];
p1.name = @"Allen";
p1.age = 21;
Person *p2 = [[Person alloc] init];
p2.name = @"Amy";
p2.age = 42;
Person *p3 = [[Person alloc] init];
p3.name = @"Lee";
p3.age = 53;
可以用KVC对集合进行操作:
NSArray *people = @[p1, p2, p3];
NSArray *names = [people valueForKey:@"name"]; //直接返回属性集合
NSUInteger ageSum = [[people valueForKeyPath:@"@sum.age"] integerValue]; //对某个属性求和
NSUInteger ageMax = [[people valueForKeyPath:@"@max.age"] integerValue];//对某个属性求最大值
NSUInteger ageMin = [[people valueForKeyPath:@"@min.age"] integerValue];//对某个属性求最小值
double ageAvg = [[people valueForKeyPath:@"@avg.age"] doubleValue];//对某个属性求平均
甚至更进一步,可以对数组成员的属性层层嵌套求值:
NSUInteger nameLengthTotal = [[people valueForKeyPath:@"@sum.name.length"] integerValue];
以下方法遍历数组中的对象name属性,转为大写,再把所有大写字符串放入新数组:
NSArray *upNames = [people valueForKeyPath:@"name.uppercaseString"];
// 得到["ALLEN", "AMY", "LEE"]
最后,提醒一下,KVC对集合操作虽然方便,但比同等循环遍历要慢很多,还是那句话“没有银弹”,只要在适合场景下使用,绝对能起到事半功倍的效果。
网友评论