How to sort NSArray of objects based on one attribute

Jackelope11 picture Jackelope11 · Jun 6, 2011 · Viewed 20.3k times · Source

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?

Answer

Dancreek picture Dancreek · Jun 6, 2011

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.