Sorting By Functions in Objective-C

Our first example demonstrates sorting collections using custom comparison functions in Objective-C. We’ll explore how to sort strings by their length and custom objects by a specific property.

#import <Foundation/Foundation.h>

@interface Person : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;

- (instancetype)initWithName:(NSString *)name age:(NSInteger)age;

@end

@implementation Person

- (instancetype)initWithName:(NSString *)name age:(NSInteger)age {
    self = [super init];
    if (self) {
        _name = [name copy];
        _age = age;
    }
    return self;
}

- (NSString *)description {
    return [NSString stringWithFormat:@"{name: %@, age: %ld}", self.name, (long)self.age];
}

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // Sorting strings by length
        NSMutableArray *fruits = [@[@"peach", @"banana", @"kiwi"] mutableCopy];
        
        [fruits sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            return [@([(NSString *)obj1 length]) compare:@([(NSString *)obj2 length])];
        }];
        
        NSLog(@"%@", fruits);
        
        // Sorting custom objects by age
        NSMutableArray *people = [NSMutableArray array];
        [people addObject:[[Person alloc] initWithName:@"Jax" age:37]];
        [people addObject:[[Person alloc] initWithName:@"TJ" age:25]];
        [people addObject:[[Person alloc] initWithName:@"Alex" age:72]];
        
        [people sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            Person *p1 = (Person *)obj1;
            Person *p2 = (Person *)obj2;
            return [@(p1.age) compare:@(p2.age)];
        }];
        
        NSLog(@"%@", people);
    }
    return 0;
}

In this Objective-C example, we implement custom sorting for both strings and custom objects:

  1. We start by sorting an array of fruits based on their string length. We use the sortUsingComparator: method, which takes a block that defines our custom comparison logic.

  2. For sorting custom objects, we define a Person class with name and age properties. We then create an array of Person objects and sort them based on their age.

  3. The sortUsingComparator: method is used again for sorting the people array. The comparator block compares the age property of two Person objects.

  4. We use NSLog to print the sorted arrays.

To run this program, save it as a .m file (e.g., SortingByFunctions.m) and compile it using:

$ clang -framework Foundation SortingByFunctions.m -o SortingByFunctions
$ ./SortingByFunctions

The output will show the sorted arrays:

(
    kiwi,
    peach,
    banana
)
(
    "{name: TJ, age: 25}",
    "{name: Jax, age: 37}",
    "{name: Alex, age: 72}"
)

This example demonstrates how to implement custom sorting logic in Objective-C, which is particularly useful when you need to sort collections based on specific criteria or properties of custom objects.