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?
Asked
Active
Viewed 2.1k times
30

Jackelope11
- 1,181
- 4
- 15
- 31
-
2Have a look at [this question](http://stackoverflow.com/questions/1844031/how-to-sort-nsmutablearray-using-sortedarrayusingdescriptors). I think it will help you. – retrodrone Jun 06 '11 at 17:56
-
It is helpful but so complex - I have a hard time understanding it, thanks though. – Jackelope11 Jun 06 '11 at 17:59
-
1Try this.. http://stackoverflow.com/a/34610703/3908884 – Meet Doshi Jan 05 '16 at 11:37
2 Answers
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.

neowinston
- 7,584
- 10
- 52
- 83

Dancreek
- 9,524
- 1
- 31
- 34
-
3Thank you so much, this will save me hours and that means a lot when the deadline is in a week and a half. – Jackelope11 Jun 06 '11 at 20:31
-
Yup, thank you... Sometimes, a decent example as the only way to cope with this over-bloated Objective-C coding. – Mike Gledhill Jul 04 '16 at 10:49
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];`

Programming Learner
- 4,351
- 3
- 22
- 34