Sorting
Foundation gives you three ways to sort a collection, each suited to a different situation:
| Technique | Method | Use when |
|---|---|---|
| selector | sortedArrayUsingSelector:@selector(compare:) |
the elements already know how to compare themselves |
| comparator block | sortedArrayUsingComparator:^… |
you need custom logic |
| sort descriptors | sortedArrayUsingDescriptors: |
sorting objects by one or more properties |
NSArray methods return a new sorted array; NSMutableArray has sortUsing… variants that sort in place.
Sorting with a selector
Strings, numbers and dates implement compare:, so they sort with one line:
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSArray *names = @[@"mango", @"apple", @"Cherry", @"banana"];
NSArray *byCompare = [names sortedArrayUsingSelector:@selector(compare:)];
NSArray *ignoreCase = [names sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
NSLog(@"compare: %@", [byCompare componentsJoinedByString:@" "]);
NSLog(@"caseInsensitiveCompare: %@", [ignoreCase componentsJoinedByString:@" "]);
NSArray *nums = @[@10, @2.5, @-4, @7];
NSLog(@"numbers: %@", [[nums sortedArrayUsingSelector:@selector(compare:)] componentsJoinedByString:@" "]);
}
return 0;
}compare: Cherry apple banana mango
caseInsensitiveCompare: apple banana Cherry mango
numbers: -4 2.5 7 10
Plain compare: is case-sensitive and puts uppercase letters before lowercase ones, which is why Cherry came first. For text shown to users, localizedCaseInsensitiveCompare: is the usual choice on Apple platforms.
Comparator blocks
A comparator block receives two objects and returns an NSComparisonResult:
| Return | Meaning |
|---|---|
NSOrderedAscending (-1) |
the first object goes first |
NSOrderedSame (0) |
they're equal for sorting purposes |
NSOrderedDescending (1) |
the second object goes first |
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSArray *words = @[@"kiwi", @"fig", @"banana", @"plum", @"apple"];
// Shortest first; equal lengths alphabetically
NSArray *byLength = [words sortedArrayUsingComparator:^NSComparisonResult(NSString *a, NSString *b) {
if (a.length < b.length) return NSOrderedAscending;
if (a.length > b.length) return NSOrderedDescending;
return [a compare:b];
}];
NSLog(@"by length: %@", [byLength componentsJoinedByString:@" "]);
// Descending numbers: just swap the operands
NSArray *scores = @[@71, @98, @85];
NSArray *highFirst = [scores sortedArrayUsingComparator:^NSComparisonResult(NSNumber *a, NSNumber *b) {
return [b compare:a];
}];
NSLog(@"high first: %@", [highFirst componentsJoinedByString:@" "]);
}
return 0;
}by length: fig kiwi plum apple banana
high first: 98 85 71
Sorting custom objects
For your own classes, either add a compare: method, use a comparator, or use NSSortDescriptor with property names:
#import <Foundation/Foundation.h>
@interface Student : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic) NSInteger grade;
+ (instancetype)studentNamed:(NSString *)name grade:(NSInteger)grade;
@end
@implementation Student
+ (instancetype)studentNamed:(NSString *)name grade:(NSInteger)grade {
Student *s = [self new];
s.name = name;
s.grade = grade;
return s;
}
@end
void printAll(NSString *title, NSArray *students) {
NSMutableArray *parts = [NSMutableArray array];
for (Student *s in students) {
[parts addObject:[NSString stringWithFormat:@"%@(%ld)", s.name, (long)s.grade]];
}
NSLog(@"%@: %@", title, [parts componentsJoinedByString:@" "]);
}
int main(void) {
@autoreleasepool {
NSArray *cls = @[[Student studentNamed:@"Noah" grade:88],
[Student studentNamed:@"Emma" grade:95],
[Student studentNamed:@"Liam" grade:88],
[Student studentNamed:@"Ava" grade:72]];
NSSortDescriptor *byGrade = [NSSortDescriptor sortDescriptorWithKey:@"grade" ascending:NO];
NSSortDescriptor *byName = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
printAll(@"by name", [cls sortedArrayUsingDescriptors:@[byName]]);
printAll(@"by grade, then name", [cls sortedArrayUsingDescriptors:@[byGrade, byName]]);
}
return 0;
}by name: Ava(72) Emma(95) Liam(88) Noah(88)
by grade, then name: Emma(95) Liam(88) Noah(88) Ava(72)
With several descriptors, the second one only breaks ties of the first (Noah and Liam both have 88). Sort descriptors use Key-Value Coding to read the properties by name.
Sorting in place and stability
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSMutableArray *tasks = [@[@"b:write", @"a:plan", @"b:test", @"a:design", @"c:ship"] mutableCopy];
// Sort by the priority letter only; NSSortStable keeps equal items in their original order
[tasks sortWithOptions:NSSortStable usingComparator:^NSComparisonResult(NSString *x, NSString *y) {
return [[x substringToIndex:1] compare:[y substringToIndex:1]];
}];
NSLog(@"%@", [tasks componentsJoinedByString:@" "]);
}
return 0;
}a:plan a:design b:write b:test c:ship
A stable sort keeps equal elements in their original relative order: b:write stays before b:test. Pass NSSortStable whenever that matters, because the default sort makes no such promise.
Test yourself
What should a comparator return when the first object should come first?
- NSOrderedDescending
- NSOrderedSame
- NSOrderedAscending
- YES
How do you sort an array of NSNumbers from largest to smallest with a comparator?
- return [a compare:b];
- return [b compare:a];
- return a > b;
- return NSOrderedSame;
With descriptors @[byGrade, byName], when is byName used?
- Always first
- Only to break ties in grade
- Never
- Only for ascending sorts