2

I have a NSMutableArray that has custom objects in it. Each object does have a name attribute. Is there a way to use

[myArray    sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]

on the name somehow? Like

[myArray.name sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]

Or am I better off writing a sort function for my custom class to sort by name? Thanks.

Crystal
  • 25,222
  • 53
  • 203
  • 370

3 Answers3

11

In this case you need to use a NSSortDescriptor.

NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
NSArray* sortedArray = [myArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
gcamp
  • 14,491
  • 4
  • 52
  • 81
4

There are several ways to achieve this, one would be to define your own comparison method, as others have suggested, but if it's just a one-off thing, you could also use the new NSComparator API to use a block for sorting:

NSArray *sortedArray = [array sortedArrayUsingComparator:^(id obj1, id obj2) {
    return [[(MyClass *)obj1 name] caseInsensitiveCompare:[(MyClass *)obj2 name]];
}];
omz
  • 52,281
  • 5
  • 125
  • 139
0

I think this answer is what you're looking for.

How to sort an NSMutableArray with custom objects in it?

Community
  • 1
  • 1
jaminguy
  • 25,490
  • 2
  • 20
  • 21