Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort NSArray of objects based on one attribute

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?

like image 836
Jackelope11 Avatar asked Jun 06 '11 17:06

Jackelope11


People also ask

How do you sort a list of objects based on an attribute of the objects in JavaScript?

In JavaScript, we use the sort() function to sort an array of objects. The sort() function is used to sort the elements of an array alphabetically and not numerically. To get the items in reverse order, we may use the reverse() method.

How do you sort an array of objects?

To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.

How do you sort an array of objects in Objective C?

The trick to sorting an array is a method on the array itself called "sortedArrayUsingDescriptors:". The method takes an array of NSSortDescriptor objects. These descriptors allow you to describe how your data should be sorted.


1 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.

like image 58
Dancreek Avatar answered Sep 19 '22 11:09

Dancreek