Friday, January 31, 2014

Sorting NSNumbers in a NSArray using sortedArrayUsingComparator block

An efficient method to sort an array is to employ the sortedArrayUsingComparator method for NSArray.

NSArray *myArray = @[@20, @30, @10];
    
NSArray *mySortedArray = [myArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
     if ([obj1 intValue] > [obj2 intValue])
         return NSOrderedDescending;
     else if ([obj1 intValue] < [obj2 intValue])
         return NSOrderedAscending;
     return NSOrderedSame;
}];
    
NSLog(@"%i",[[mySortedArray objectAtIndex:0] intValue]);
NSLog(@"%i",[[mySortedArray objectAtIndex:1] intValue]);
NSLog(@"%i",[[mySortedArray objectAtIndex:2] intValue]); 
An array of integer literals is created and sorted by calling sortedArrayUsingComparator which accepts a NSComparator block. Objects are compared to one another to sort them in an ascending order and the NSLogs return the values 10, 20 and 30. To sort in a descending order, reverse the ascending and descending statements.

NSArray *myArray = @[@20, @30, @10];
    
NSArray *mySortedArray = [myArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
     if ([obj1 intValue] > [obj2 intValue])
         return NSOrderedAscending;
     else if ([obj1 intValue] < [obj2 intValue])
         return NSOrderedDescending;
     return NSOrderedSame;
}];
    
NSLog(@"%i",[[mySortedArray objectAtIndex:0] intValue]);
NSLog(@"%i",[[mySortedArray objectAtIndex:1] intValue]);
NSLog(@"%i",[[mySortedArray objectAtIndex:2] intValue]);

Now the logs show 30, 20 and 10.

No comments:

Post a Comment