How to sort NSArray of objects based on one attribute

20,450

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.

Share:
20,450
Jackelope11
Author by

Jackelope11

(Your about me is currently blank. )

Updated on March 15, 2020

Comments

  • Jackelope11
    Jackelope11 about 4 years

    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?

    • retrodrone
      retrodrone almost 13 years
      Have a look at this question. I think it will help you.
    • Jackelope11
      Jackelope11 almost 13 years
      It is helpful but so complex - I have a hard time understanding it, thanks though.
    • Meet Doshi
      Meet Doshi over 8 years
  • Jackelope11
    Jackelope11 almost 13 years
    Thank you so much, this will save me hours and that means a lot when the deadline is in a week and a half.
  • Dancreek
    Dancreek almost 13 years
    No problem. Glad I could help.
  • Mike Gledhill
    Mike Gledhill almost 8 years
    Yup, thank you... Sometimes, a decent example as the only way to cope with this over-bloated Objective-C coding.