Sorting NSMutableArrays

Sorting NSMutableArrays

For whatever reason, sorting arrays in Objective-C perplexes a great many budding iOS developers.

However, it can be entirely straightforward.

The example below takes a mutable array (in this case, a set of businesses) and sorts them either by a point value or by a distance value, depending upon the state of a button from the UI.

The heavy lifting is all done by the comparison functions compareProximity and comparePoints.

The code is fairly self explanatory. I’ve written the comparison functions in a way as to be totally explicit about what values need to be returned.

Pay particular attention; the comparison function comparePoints is written to sort the array in descending point order; compareProximity sorts the array in ascending distance order.

// Compare Result for Sorting by Proximity
NSComparisonResult compareProximity(Business *b1, Business * b2, void * context) {
	if (b1.distance<b2.distance) {return NSOrderedAscending;}
	if (b1.distance>b2.distance) {return NSOrderedDescending;}
	if (b1.distance==b2.distance) {return NSOrderedSame;}

	return NSOrderedSame;
}

// Compare Result for Sorting by Points, Descending
NSComparisonResult comparePoints(Business *b1, Business * b2, void * context) {
	if (b1.points<b2.points) {return NSOrderedDescending;}
	if (b1.points>b2.points) {return NSOrderedAscending;}
	if (b1.points==b2.points) {return NSOrderedSame;}

	return NSOrderedSame;
}

// React to a button push from the screen
-(IBAction)doSort:(id)id {
	UIButton* btn = (UIButton*)id;

        // Toggle button on display
	if (btn.tag==0) {
		[btn setImage:[UIImage imageNamed:@"points_image.png"] 
                        forState:UIControlStateNormal];
		btn.tag=1;
		}
	else {
		[btn setImage:[UIImage imageNamed:@"proximity_image.png"]
                        forState:UIControlStateNormal];
		btn.tag=0;
		}

        // Order Elements (Perform the Sort)
	[self orderElements];

        // Refresh the data in UITableView
	[self.table reloadData];
}

// Perform the sort, depending upon button state
-(void)orderElements {
	if (self.sortButton.tag==1) {
		[self.businesses sortUsingFunction:compareProximity context:NULL];
	        }
	else {
		[self.businesses sortUsingFunction:comparePoints context:NULL];
	        }
}
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