-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!

1

1 Answer 1

6
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:sortDescriptors];
Sign up to request clarification or add additional context in comments.

5 Comments

Is it possible that instead of an NSArray the output is an NSMutableArray, specifically the same array that I use (called array)?
Have you even looked in the documentation? Your question can easily be answered from the docs.
@Kevin: Look in the NSMutableArray class reference. There's an entire section there about sorting.
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.
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...: developer.apple.com/library/mac/documentation/Cocoa/Reference/…. Just pick the one that is equivalent to the NSArray example above.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.