Finding maximum numeric value in NSArray
Asked Answered
S

4

53

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.

Sexpot answered 20/6, 2010 at 18:58 Comment(0)
B
179

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

Busby answered 20/6, 2010 at 19:39 Comment(3)
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? #4499609Origen
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 NSStrings or anything that implements compare:.Phyte
L
1
NSArray *  test= @[@3, @67, @23, @67, @67];
int maximumValue = [[test valueForKeyPath: @"@max.self"] intValue];
 NSLog(@" MaximumValue = %d", maximumValue);

// Maximum = 67
Lateritious answered 12/3, 2016 at 18:48 Comment(0)
A
1

Here is the swift version

let maxValue =  (numbers.value(forKeyPath: "@max.self") as! Double)
Aldridge answered 9/7, 2018 at 10:51 Comment(0)
T
0

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);
Tricotine answered 3/11, 2017 at 5:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.