Archive for June, 2010

Adding easy to use sorting features to Objective-C arrays

by Ali. 1 Comment

Apart from how powerful and flexible NSArray in Objective-C is, there are times that you need to sort many arrays throughout the projects.

The standard way of sorting arrays in Objective-C is to use one of:

  • sortedArrayHint
  • sortedArrayUsingFunction:context:
  • sortedArrayUsingFunction:context:hint:
  • sortedArrayUsingDescriptors:
  • sortedArrayUsingSelector:

(See the official documentation)

But what if all you need is just a simple sort, available in different classes and across many projects?

Using sortedArrayUsingSelector:, for example, will need you to type in something like this as many times as you want to sort an array:

NSArray *array = [[NSArray alloc] initWithObjects:
@"Sally", @"Jake", @"Alex", @"Tim", @"Tammy", nil];
NSArray *sortedArray = [array sortedArrayUsingSelector:
@selector(caseInsensitiveCompare:)];

To make your life easier, Apple has made categories available for you to simply extend the functionality of a any class (NSArray in here) visible to the entire project. As you might wonder, you don’t even need to have access to the source code of the class you are extending.

Getting Started

To keep things clean an tidy, add a new Objective-C class to your project (File > New File…) and call it Categories. Make sure you create the .h file too.

Adding a new Objective-C class in Xcode

 

Then replace the interface with this code:

@interface NSArray (NSArraySortExtensions)
 
- (NSArray *)sortAscending;
 
@end

And the implementation with this code:

#import "Categories.h"
 
@implementation NSArray(NSArraySortExtensions)
 
- (NSArray *)sortAscending {
  return [self sortedArrayUsingSelector:
    @selector(caseInsensitiveCompare:)];
}
 
@end

Now go back to your class, where you want to use sorted arrays and first import the newly made class:

#import "Categories.h"

Now you can easily sort an array by sending a very short message to NSArray:

NSArray *array = [[NSArray alloc] initWithObjects:
    @"Sally", @"Jake", @"Alex", @"Tim", @"Tammy", nil];
NSArray *sortedArray = [array sortAscending];

or even:

NSArray *array = [[[NSArray alloc] initWithObjects:
    @"Sally", @"Jake", @"Alex", @"Tim", @"Tammy", nil]
    sortAscending];

You can add more methods to the category and make NSArray even more powerful.

government,politics news,politics news,politics