Objective C - Sort an array of string

you need to use

-[NSArray sortedArrayUsingSelector:]

or

-[NSMutableArray sortUsingSelector:] and pass @selector(compare:) as the parameter.

here's a link to the answer Sort NSArray of date strings or objects


Here's what I ended up using - works like a charm:

[categoryArray sortedArrayWithOptions:0
               usingComparator:^NSComparisonResult(id obj1, id obj2)
{
    id<SelectableCategory> cat1 = obj1;
    id<SelectableCategory> cat2 = obj2;
    return [cat1.name compare:cat2.name options:NSCaseInsensitiveSearch];
}];

SelectableCategory is just a @protocol SelectableCategory <NSObject> defining the category with all its properties and elements.


For just sorting array of strings:

sorted = [array sortedArrayUsingSelector:@selector(compare:)];

For sorting objects with key "name":

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(compare:)];
sorted = [array sortedArrayUsingDescriptors:@[sort]];

Also, instead of compare: you can use:

  • caseInsensitiveCompare:

  • localizedCaseInsensitiveCompare: