22

I have to sort an array of objects by a property of the objects that is a string. How can I do this?

Chris Knadler
  • 2,819
  • 2
  • 26
  • 32
Andrea Mario Lufino
  • 7,921
  • 12
  • 47
  • 78

3 Answers3

41

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

Community
  • 1
  • 1
Jason Cragun
  • 3,233
  • 1
  • 26
  • 27
17

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:

Borzh
  • 5,069
  • 2
  • 48
  • 64
8

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.

craned
  • 2,991
  • 2
  • 34
  • 38