Reputation: 1
I have sorted some NSMutableArray
, that has dictionaries with many fields .
2 fields are interested me the most , the date and some count integer number .
I have sorted the array with date :
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"dateCreated" ascending:YES];
sortedWithDates=[sortedWithDates sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
Now, i want to take only the objects in the array -for today, and sort them again according to this count integer(highest first) .
Is there a simple way to do that with the same NSSortDescriptor
class ?
Thank you .
Upvotes: 0
Views: 84
Reputation: 124997
Is there a simple way to do that with the same NSSortDescriptor class ?
Yes, there's a very simple way. You can pass more than one sort descriptor to -sortedArrayUsingDescriptors:
. Items that are equal according to the first descriptor will be sorted according to the second (or third, etc.).
From the docs:
The first descriptor specifies the primary key path to be used in sorting the receiving array’s contents. Any subsequent descriptors are used to further refine sorting of objects with duplicate values.
So your code could look like this:
NSSortDescriptor *date = [[NSSortDescriptor alloc] initWithKey:@"dateCreated" ascending:YES];
NSSortDescriptor *count = [[NSSortDescriptor alloc] initWithKey:@"count" ascending:YES];
sortedWithDates=[sortedWithDates sortedArrayUsingDescriptors:@[date, count]];
Note: I used the newer object literal syntax for the array of descriptors. That's just a matter of style -- your +arrayWithObjects:
call is fine too.
Upvotes: 3
Reputation: 52538
You can use the same descriptor as often as you like. Of course, the descriptor that you created will always sort on "dateCreated" in ascending order, but it can be used to sort any number of arrays.
Instead of [NSArray arrayWithObjects:descriptor,nil] you can use the modern syntax @[descriptor]. @[object ... ] creates an NSArray containing the objects between the square brackets.
Upvotes: 0