I have an NSArray of NSNumbers and want to find the maximum value in the array. Is there any built in functionality for doing so? I am using iOS4 GM if that makes any difference.
Finding maximum numeric value in NSArray
Asked Answered
The KVC approach looks like this:
int max = [[numbers valueForKeyPath:@"@max.intValue"] intValue];
or
NSNumber * max = [numbers valueForKeyPath:@"@max.intValue"];
with numbers as an NSArray
Thanks, I was trying to use valueForKeyPath but wasn't using .intValue so it wasn't working. –
Sexpot
What if some of items of NSArray are NSNulls? #4499609 –
Origen
In fact, it would be better to use
@"@max.self"
. Since @max
uses compare:
, it needs actual objects : with intValue
, not only do you lose precision, but valueForKeyPath:
has to recreate NSNumbers to work with. As a bonus, it also works with NSString
s or anything that implements compare:
. –
Phyte NSArray * test= @[@3, @67, @23, @67, @67];
int maximumValue = [[test valueForKeyPath: @"@max.self"] intValue];
NSLog(@" MaximumValue = %d", maximumValue);
// Maximum = 67
Here is the swift version
let maxValue = (numbers.value(forKeyPath: "@max.self") as! Double)
Hope will helpful to you.
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);
© 2022 - 2024 — McMap. All rights reserved.