【发布时间】:2011-03-06 01:32:42
【问题描述】:
我有一个由 NSNumbers 组成的 NSArray,并想在数组中找到最大值。是否有任何内置功能可以这样做?如果这有什么不同,我正在使用 iOS4 GM。
【问题讨论】:
标签: iphone objective-c nsarray
我有一个由 NSNumbers 组成的 NSArray,并想在数组中找到最大值。是否有任何内置功能可以这样做?如果这有什么不同,我正在使用 iOS4 GM。
【问题讨论】:
标签: iphone objective-c nsarray
KVC 方法如下所示:
int max = [[numbers valueForKeyPath:@"@max.intValue"] intValue];
或
NSNumber * max = [numbers valueForKeyPath:@"@max.intValue"];
将数字作为 NSArray
【讨论】:
@"@max.self"会更好。由于@max 使用compare:,它需要实际对象:使用intValue,不仅会丢失精度,而且valueForKeyPath: 必须重新创建NSNumbers 才能使用。作为奖励,它也适用于 NSStrings 或任何实现 compare: 的东西。
NSArray * test= @[@3, @67, @23, @67, @67];
int maximumValue = [[test valueForKeyPath: @"@max.self"] intValue];
NSLog(@" MaximumValue = %d", maximumValue);
// Maximum = 67
【讨论】:
这里是 swift 版本
let maxValue = (numbers.value(forKeyPath: "@max.self") as! Double)
【讨论】:
希望对你有所帮助。
NSArray * arrayOfBarGraphValues = @[@65, @45, @47 ,@87 , @46, @66 ,@77 ,@47 ,@79 ,@78 ,@87 ,@78 ,@87 ];
int maxOfBarGraphValues = [[arrayOfBarGraphValues valueForKeyPath: @"@max.self"] intValue];
NSLog(@" MaximumValue Of BarGraph = %d", maxOfBarGraphValues);
【讨论】: