Objective-C Language NSArray Sorting Arrays


The most flexible ways to sort an array is with the sortedArrayUsingComparator: method. This accepts an ^NSComparisonResult(id obj1, id obj2) block.

 Return Value            Description
 NSOrderedAscending      obj1 comes before obj2
 NSOrderedSame           obj1 and obj2 have no order
 NSOrderedDescending     obj1 comes after obj2


   NSArray *categoryArray = @[@"Apps", @"Music", @"Songs",
                     @"iTunes", @"Books", @"Videos"];
    NSArray *sortedArray = [categoryArray sortedArrayUsingComparator:
^NSComparisonResult(id obj1, id obj2) {
    if ([obj1 length] < [obj2 length]) {
        return NSOrderedAscending;
    } else if ([obj1 length] > [obj2 length]) {
        return NSOrderedDescending;
    } else {
        return NSOrderedSame;

 NSLog(@"%@", sortedArray);