I need to search a mutable array for the maximum value and return its position as well as value. I’d only like to iterate through the array once and I’m not sure if that’s possible
an example of what I’m trying to accomplish can be demonstrated below
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int i = 0; i<20; i++)
[array addObject:[NSNumber numberWithInteger:(arc4random()%200)]];
NSObject *max = [array valueForKeyPath:@"@max.self"];
the max object only seems to contain the value (and not the position). this can be demonstrated through the debugger with print-object max
Any advice out there?
Using
valueForKeyPath:@"@max.self"is great, but only if you want the maximum value.To know both index and value in one iteration, I’d use
enumerateWithBlock:Quite more code, but you’re iterating only once in the array.