Monday, 20 May 2013

Get The Max Value from an NSArray



-(void)findMax
{
    NSArray *numberArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:10], [NSNumber numberWithInt:20], [NSNumber numberWithInt:1000], nil];
    NSInteger highestNumber;
    NSInteger numberIndex;
    for (NSNumber *theNumber in numberArray)
    {
        if ([theNumber integerValue] > highestNumber) {
            highestNumber = [theNumber integerValue];
            numberIndex = [numberArray indexOfObject:theNumber];
        }
    }
    NSLog(@"Highest number: %i at index: %i", highestNumber, numberIndex);
}


Out Put :

Highest number: 1000 at index: 2


Using KVC


[self setValue:[NSNumber numberWithInt:10] forKey:@"number1"];
[self setValue:[NSNumber numberWithInt:20] forKey:@"number2"];
[self setValue:[NSNumber numberWithInt:1000] forKey:@"number3"];
   
NSArray *numberArray = [NSArray arrayWithObjects:[self valueForKey:@"number1"], [self valueForKey:@"number2"], [self valueForKey:@"number3"], nil];
    
    
    int max = [[numberArray valueForKeyPath:@"@max.intValue"] intValue];
    
   NSLog(@"Highest number: %i",max);

Out Put :




Highest number: 1000

No comments:

Post a Comment