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
2010-06-20 19:26:38
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
2010-06-20 19:33:32
+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
2010-06-20 19:39:29
Thanks, I was trying to use valueForKeyPath but wasn't using .intValue so it wasn't working.
Adam S.
2010-06-20 20:11:26