Sorting an NSMutableArray using a block

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];
	}
}];
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s