-1

Possible Duplicate:
How to sort an NSMutableArray with custom objects in it?

I have a custom class where one of the values are names. Imagine the class is called Person. I would like to sort these values, which I am keeping in an NSMutableArray according to the name variable, however:

[testarray sortUsingSelector:@selector(compare:)];

will only work only an array of strings.

I am trying to work out how I can arrange the array alphabetically given that:

Person *person;
person = [array objectAtIndex:0];
[person name];

Person *person;
person = [array objectAtIndex:1];
[person name];

How can I compare the two? Thanks!

Community
  • 1
  • 1
Kevin
  • 1,469
  • 2
  • 19
  • 28
  • And a bazillion others: http://stackoverflow.com/search?q=%5Bobjc%5D+sort+array+custom+object – jscs May 07 '12 at 18:20

1 Answers1

6
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:sortDescriptors];
Ole Begemann
  • 135,006
  • 31
  • 278
  • 256
  • Is it possible that instead of an NSArray the output is an NSMutableArray, specifically the same array that I use (called array)? – Kevin May 07 '12 at 14:03
  • 1
    Have you even looked in the documentation? Your question can easily be answered from the docs. – Ole Begemann May 07 '12 at 14:16
  • 1
    @Kevin: Look in the NSMutableArray class reference. There's an entire section there about sorting. – Peter Hosey May 07 '12 at 23:29
  • I did try looking in the NSMutableArray class reference but there is no reference to sorting. Sorting is found in the NSArray class, which for what is need is not very useful. Thanks for any light you might shed. – Kevin May 08 '12 at 13:19
  • 1
    It's called "Rearranging Content" instead of "Sorting" in the documentation but honestly, the list of all `NSMutableArray` methods is not very long and five of them begin with `sort...`: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/doc/uid/20000138-SW6. Just pick the one that is equivalent to the `NSArray` example above. – Ole Begemann May 08 '12 at 13:23