Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting NSMutableArray By Object's Property

So this is a rather basic question regarding the best way to sort an NSMutableArray of custom objects.

I have a an NSMutableArray of custom objects, each object with an NSString and NSDate that go together. I need to sort the array by the newest object (so latest NSDate), and I'm pretty sure I could simply use NSDate compare: NSDate if this was an array of just NSDate, but since I need all objects to be sorted and not just the date, I'm not sure if I can use that method.

In terms of pseudo-code, I need to: Look at individual object, determine if the current object's NSDate is the next biggest in the array, and if it is, move the object, not just the date.

Again, this is something I was even hesitant to ask since it's so basic but I don't want to go writing some grossly inefficient method if there is a pre-existing class method that will essentially do what I want, search an array of object's sub properties and sort the objects according to the subproperties.

Thanks for any help.

like image 920
Rich Haygren Avatar asked Aug 09 '11 19:08

Rich Haygren


People also ask

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.

How do you sort a string array in Objective C?

For just sorting array of strings: sorted = [array sortedArrayUsingSelector:@selector(compare:)]; For sorting objects with key "name": NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(compare:)]; sorted = [array sortedArrayUsingDescriptors:@[sort]];

What is NSMutableArray Objective C?

The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray . NSMutableArray is “toll-free bridged” with its Core Foundation counterpart, CFMutableArray .


2 Answers

NSSortDescriptorss make this really simple. With NSMutableArray you can sort the existing array using sortUsingDescriptors: and with immutable arrays you create a new array using sortedArrayUsingDescriptors:

//This will sort by stringProperty ascending, then dateProperty ascending [mutable_array sortUsingDescriptors:  @[   [NSSortDescriptor sortDescriptorWithKey:@"stringProperty" ascending:YES],   [NSSortDescriptor sortDescriptorWithKey:@"dateProperty" ascending:YES]   ]]; 
like image 110
Joe Avatar answered Oct 05 '22 05:10

Joe


This little snippet worked great for me:

[students sortUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]]]; 
like image 39
funroll Avatar answered Oct 05 '22 04:10

funroll