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.

Adam S.
  • 1,251
  • 1
  • 12
  • 16

4 Answers4

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

sergiobuj
  • 2,318
  • 2
  • 21
  • 24
  • 1
    Thanks, I was trying to use valueForKeyPath but wasn't using .intValue so it wasn't working. – Adam S. Jun 20 '10 at 20:11
  • What if some of items of NSArray are NSNulls? http://stackoverflow.com/questions/4499109/how-to-tell-nsarray-valueforkeypath-to-ignore-nsnulls – HiveHicks Dec 21 '10 at 13:31
  • 14
    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:`. – n-b Nov 23 '12 at 07:49
1
NSArray *  test= @[@3, @67, @23, @67, @67];
int maximumValue = [[test valueForKeyPath: @"@max.self"] intValue];
 NSLog(@" MaximumValue = %d", maximumValue);

// Maximum = 67
joan
  • 2,407
  • 4
  • 29
  • 35
1

Here is the swift version

let maxValue =  (numbers.value(forKeyPath: "@max.self") as! Double)
Zulqarnain Mustafa
  • 1,615
  • 2
  • 22
  • 25
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);
BuLB JoBs
  • 841
  • 4
  • 20