Sorting an NSMutableArray using a block

November 09, 2010 - hive-memory objective-c

Now we have blocks in Objective-C, we no longer need to define standalone methods to implement a custom array sort. However, I’m always forgetting the exact syntax, so, mostly as a reminder to myself:

[alerts sortUsingComparator:(NSComparator)^(Alert *a1, Alert *a2) {
	if ([a1.severity compare:a2.severity] == NSOrderedSame) {
		return [a1.timeRaised compare:a2.timeRaised];
	} else {
		return [a1.severity compare:a2.severity];
	}
}];