Possible Duplicate:
How to sort an NSMutableArray with custom objects in it?
How does one sort an array of objects by accessing their NSDate properties?
I know one can use [mutableArray sortUsingSelector:@selector(compare:)];
on an array of dates, but how does one do it by accessing a NSDate property on each element in the array, sorting the objects by earliest date to latest date?
The code snippet assumes that your array of objects contains Date objects. If it contains Date strings, use the map method to convert the strings to Date objects before calling sort (). The code snippet shows how to sort an array of objects by a date property if your starting point is an array containing objects with date strings.
There are two ways you can sort an object array by a specific property, using Array.Sort () method and by using LINQ query. The people array in the above example contains objects of Person class. You cannot use Array.Sort (people) because array contains objects, not primitive values.
In the main () method, we’ve created an array list of custom objects list, initialized with 5 objects. For sorting the list with the given property, we use the list ‘s sort () method. The sort () method takes the list to be sorted (final sorted list is also the same) and a comparator.
We can sort and filter data on various conditions, and sorting by the value of a string property is a common one. For example, suppose we have a list of students with their firstName and lastName: We could sort these students by either their firstName or lastName.
Thanks for all the answers, I came across this answer that solved my problem.Check NSGod's answer
Here is the code thanks to user: NSGod:
NSSortDescriptor *dateDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"startDateTime" ascending:YES]; NSArray *sortDescriptors = [NSArray arrayWithObject:dateDescriptor]; NSArray *sortedEventArray = [nodeEventArray sortedArrayUsingDescriptors:sortDescriptors];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With