Objective-C stable multi-key sort with nulls last
Objective-C
#import <Foundation/Foundation.h>
static NSArray<NSDictionary *> *SortRecords(NSArray<NSDictionary *> *records) {
NSMutableArray<NSNumber *> *order = [NSMutableArray array];
for (NSUInteger i = 0; i < records.count; i++) [order addObject:@(i)];
[order sortUsingComparator:^NSComparisonResult(NSNumber *ia, NSNumber *ib) {
NSDictionary *a = records[ia.unsignedIntegerValue], *b = records[ib.unsignedIntegerValue];
id an = a[@"name"], bn = b[@"name"];
if (an || bn) {
if (!an) return NSOrderedDescending; // nulls last
if (!bn) return NSOrderedAscending;
NSComparisonResult r = [an compare:bn options:NSCaseInsensitiveSearch];
if (r != NSOrderedSame) return r;
NSComparisonResult byAge = [(a[@"age"] ?: @0) compare:(b[@"age"] ?: @0)];
if (byAge != NSOrderedSame) return byAge;
}
return [ia compare:ib]; // original index keeps ties stable
}];
NSMutableArray *out = [NSMutableArray array];
for (NSNumber *i in order) [out addObject:records[i.unsignedIntegerValue]];
return out;
}