- (void)viewDidLoad {
[super viewDidLoad];
NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil];
CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];
CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue];
CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];
NSLog(@"%.2f\n%.2f\n%.2f\n%.2f",sum,avg,max,min);
}
另外我们经常使用 objectForKey来进行取值,当然也可以利用valueForKeyPath把数组中的对象找出来:
例如:
NSArray *dictArr = @[@{@"name":@"liugaojian",@"sex":@"man"},@{@"name":@"zhanghongjie",@"sex":@"women"},@{@"name":@"liubin",@"sex":@"man"}];
for (NSDictionary *dict in dictArr) {
if ([[dict objectForKey:@"name"]isEqualToString:@"liugaojian"]) {
NSLog(@"%@",dict[@"sex"]);
}
}
通过以上我们找出name为liugaojian的对象的sex的值
而通过valueForKeyPath我们可以得到多个结果
NSArray *array = [dictArr valueForKeyPath:@"name"];
NSLog(@"%@",array);
运行以上代码之后的结果是: