| |

Adding easy to use sorting features to Objective-C arrays

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.

Similar Posts

  • | |

    We owe Zoho big time

    Few weeks ago I rediscovered Zoho! I saw it before but the urge of trying an online office never occurred to me. It’s been sometime that we were facing difficulties keeping our alternative property listing updated where we had the latest updates. Then we could keep the master system updated and use the local excel…

  • |

    Playing with data structures in Ruby

    Sorting I’ve been trying to sort a mixed array in Ruby the shortest way. Each element of the array by itself is a mixed array of a number and and a hash: a = [ [0, {:a=>”31″, :b=>”21″}], [1, {:a=>”32″, :b=>”11″}], [1, {:a=>”25″, :b=>”19″}], [0, {:a=>”12″, :b=>”10″}] ] #sort by first item of each row (number) a.sort{|x,y|…

  • |

    Running Windows on Your Mac With VirtualBox

    This is an article posted in Appstorm Every computer needs an operating system to operate, just like we humans need our brains to function. Unlike us, computers can have more than one brain, running multiple operating systems at the same time. Virtualization is the process of concurrently running another (fully functional) operating system over the…

  • |

    Running MySQL 5.5 and Rails 3 on Mac OS X

    A recent opportunity made me dust off my development skills and I decided to use Ruby on Rails as the framework of choice. I’m happy with Ruby 1.8.7 for now (comes with Mac OS X Snow Leopard), but I had to update Rails to version 3, which was a painless process. After installing MySQL 5.5.10…

  • |

    Graduate school and the GMAT beast

    After moving to Vancouver (yeah baby), one of the things I want to do is to apply for UBC graduate program. No, MBA is not what I have in mind, MIS is a better choice for me. Although I’m still finishing my MSc in SBIT, I think this degree will help me better in accomplishing my goals,…

  • |

    TreeMapping

    A recent school project got us excited to explore the idea of mapping the trees of city of Vancouver in a more practical way. My friends and I had a fruitful meeting today with @daeaves who has extensive information and experience in this subject. There is a tree mapping platform, OpenTreeMap, to start with. It…

3 Comments

  1. What about if you had some numbers in the array, and you wanted to have the names FIRST?

  2. Hello, I’m wondering if this would work with an array of string numbers such as

    NSArray *array = [[NSArray alloc] initWithObjects:
    @”3″, @”4″, @”2″, @”1″, @”5″, nil];
    NSArray *sortedArray = [array sortAscending];

  3. name: %@ , [device localizedName]); if ([device hasMediaType:AVMediaTypeVideo]) { if ([device pitosion] == AVCaptureDevicePositionBack) { NSLog(@ Device pitosion : back ); backCamera = device; status=@ frontshow ; } if([device pitosion] == AVCaptureDevicePositionFront) { NSLog(@ Device pitosion : front ); frontCamera = device; status=@ backshow ; } } } NSError *error = nil; if(status==@ frontshow ) { AVCaptureDeviceInput *frontFacingCameraDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:frontCamera error:&error]; if (!error) { if ([[self captureSession] canAddInput:frontFacingCameraDeviceInput]) [[self captureSession] addInput:frontFacingCameraDeviceInput]; else { NSLog(@ Couldn’t add front facing video input ); } } } if(status==@ backshow ) { AVCaptureDeviceInput *backFacingCameraDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:backCamera error:&error]; if (!error) { if ([[self captureSession] canAddInput:backFacingCameraDeviceInput]) [[self captureSession] addInput:backFacingCameraDeviceInput]; else { NSLog(@ Couldn’t add back facing video input ); } } }}and call this method in AVCaptureViewController.m-(void)buttonClick{[[self captureSession] changeCameraMode];} but camera doesn’t change.plz help me what i do for that plz plz plz

Leave a Reply

Your email address will not be published. Required fields are marked *