views:

87

answers:

3

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.

A: 

Try this (I'm assuming the number is an integer but this can easily be changed if its something else):

    NSArray *numberArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:45], [NSNumber numberWithInt:100], nil];
    NSInteger highestNumber;
    NSInteger numberIndex;
    for (NSNumber *theNumber in numberArray)
    {
        if ([theNumber integerValue] > highestNumber) {
           highestNumber = [theNumber integerValue];
           numberIndex = [numberArray indexOfObject:theNumber];
        }
    }
    NSLog(@"Highest number: %d at index: %d", highestNumber, numberIndex);
macatomy
A: 

You might be able to use Kev Value Coding along with @max. I'm still new to Objective-C and someone else would need to piece together some sample code on this though.

Joost Schuur
+6  A: 

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
Thanks, I was trying to use valueForKeyPath but wasn't using .intValue so it wasn't working.
Adam S.