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?
- 
        2Have a look at this question. I think it will help you.retrodrone– retrodrone2011-06-06 17:56:12 +00:00Commented Jun 6, 2011 at 17:56
- 
        It is helpful but so complex - I have a hard time understanding it, thanks though.Jackelope11– Jackelope112011-06-06 17:59:03 +00:00Commented Jun 6, 2011 at 17:59
- 
        1Try this.. stackoverflow.com/a/34610703/3908884Meet Doshi– Meet Doshi2016-01-05 11:37:05 +00:00Commented Jan 5, 2016 at 11:37
                    
                        Add a comment
                    
                 | 
            
                
            
        
         
    2 Answers
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.
2 Comments
Jackelope11
 Thank you so much, this will save me hours and that means a lot when the deadline is in a week and a half.
  Mike Gledhill
 Yup, thank you...  Sometimes, a decent example as the only way to cope with this over-bloated Objective-C coding.
  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];`
