计算数字数组中元素的最值 & KVC用法延伸

计算数字数组中元素的最值 & KVC用法延伸

原贴地址:http://stackoverflow.com/questions/15931112/finding-the-smallest-and-biggest-value-in-nsarray-of-nsnumbers

方法一:排序

NSArray *sorted1 = [numbers sortedArrayUsingSelector:@selector(compare:)];

方法二:KVC - doubleValue

NSNumber *max=[numbers valueForKeyPath:@"@max.doubleValue"];
NSNumber *min=[numbers valueForKeyPath:@"@min.doubleValue"];

方法三:KVC - self

NSNumber *max=[numbers valueForKeyPath:@"@max.self"];
NSNumber *min=[numbers valueForKeyPath:@"@min.self"];

方法四:循环

float xmax = -MAXFLOAT;
float xmin = MAXFLOAT;
for (NSNumber *num in numbers) {
    float x = num.floatValue;
    if (x < xmin) xmin = x;
    if (x > xmax) xmax = x;
}

方法五:block遍历

__block float xmax = -MAXFLOAT;
__block float xmin = MAXFLOAT;
[numbers enumerateObjectsUsingBlock:^(NSNumber *num, NSUInteger idx, BOOL *stop) {
    float x = num.floatValue;
    if (x < xmin) xmin = x;
    if (x > xmax) xmax = x;
}];

※ 各种方法性能测试

  • demo.m

KVC使用补充

求和

NSNumber *sum = [numbers valueForKeyPath:@"@sum.floatValue"];

求平均值

NSNumber *sum = [numbers valueForKeyPath:@"@avg.floatValue"];

删除重复数据

NSArray *newArray = [numbers valueForKeyPath:@"@distinctUnionOfObjects.self"]; 

调用实例方法

NSArray *array = @[@"id", @"sex", @"age", @"homeTown"];
// 字符串变大写
NSArray *list1 = [array valueForKeyPath:@"uppercaseString"];
// 字符串变小写
NSArray *list2 = [array valueForKeyPath:@"lowercaseString"];
// 字符串首字母变大写,其它变小写
NSArray *list3 = [array valueForKeyPath:@"capitalizedString"];
……
// 其它实例方法以此类推,皆可调用!

你可能感兴趣的:(iOS)