Sorting in Objective-C

Our first example demonstrates sorting for built-in types in Objective-C. We’ll use the Foundation framework’s sorting capabilities.

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // Sorting functions work for any comparable built-in type.
        // For strings, we'll use NSArray and sortedArrayUsingSelector:
        NSArray *strs = @[@"c", @"a", @"b"];
        NSArray *sortedStrs = [strs sortedArrayUsingSelector:@selector(compare:)];
        NSLog(@"Strings: %@", sortedStrs);
        
        // An example of sorting NSNumbers (which wrap int values)
        NSArray *ints = @[@7, @2, @4];
        NSArray *sortedInts = [ints sortedArrayUsingSelector:@selector(compare:)];
        NSLog(@"Ints:    %@", sortedInts);
        
        // We can also check if an array is already in sorted order
        BOOL isSorted = [sortedInts isEqualToArray:[sortedInts sortedArrayUsingSelector:@selector(compare:)]];
        NSLog(@"Sorted:  %@", isSorted ? @"YES" : @"NO");
    }
    return 0;
}

To run the program, compile it and execute:

$ clang -framework Foundation sorting.m -o sorting
$ ./sorting
Strings: (
    a,
    b,
    c
)
Ints:    (
    2,
    4,
    7
)
Sorted:  YES

In this Objective-C example, we use NSArray’s sorting methods to sort arrays of strings and numbers. The sortedArrayUsingSelector: method is used with the compare: selector to sort the elements.

For checking if an array is sorted, we compare the original array with a sorted version of itself. If they’re equal, the original array was already sorted.

Note that Objective-C uses NSArray, which is mutable, unlike Go’s slices. If you need to modify the array in-place, you would use NSMutableArray instead.

Objective-C’s Foundation framework provides powerful sorting capabilities, but the syntax and approach differ from Go’s slices package. The concepts of sorting and checking for sortedness are similar, but the implementation details vary between the two languages.