30

I am trying to sort an array of managed objects alphabetically. The attribue that they need to be sorted by is the name of the object (NSString) with is one of the managed attributes. Currently I am putting all of the names in an array of strings and then using sortedNameArray = [sortedNameArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; and then enumerating them back into an array with the objects. This falls apart when two names are the same so I really need to be able to sort by one attribute. How should I go about doing this?

3
  • 2
    Have a look at this question. I think it will help you. Commented Jun 6, 2011 at 17:56
  • It is helpful but so complex - I have a hard time understanding it, thanks though. Commented Jun 6, 2011 at 17:59
  • 1
    Try this.. stackoverflow.com/a/34610703/3908884 Commented Jan 5, 2016 at 11:37

2 Answers 2

83

Use NSSortDescriptor. Just search the documentation on it and there some very simple examples you can copy right over. Here is a simplified example:

NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc] initWithKey:@"MyStringVariableName" ascending:YES];
NSArray *descriptors = [NSArray arrayWithObject:valueDescriptor]; 
NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:descriptors]; 

And just like that you have a sorted array.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much, this will save me hours and that means a lot when the deadline is in a week and a half.
Yup, thank you... Sometimes, a decent example as the only way to cope with this over-bloated Objective-C coding.
0

You can do this by using NSSortDescriptor,

eg.

`NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc]initWithKey:@"distance" ascending:YES];`

// Here I am sorting on behalf of distance. You should write your own key.

NSArray * descriptors = [NSArray arrayWithObject:valueDescriptor];
NSArray *sortedArray=[yourArray sortedArrayUsingDescriptors:descriptors];`

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.