Objective-C Language NSArray Sorting Arrays

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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

Example:

   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);


Got any Objective-C Language Question?