i need to sort the month and year in ascending or descending order using NSSortDescriptor i have one array
{
month = Dec;
year = 2017;
},
{
month = Oct;
year = 2017;
},
{
month = Jan;
year = 2018;
}
i used to done this code
NSSortDescriptor * sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"year" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
yeardata = [NSMutableArray arrayWithArray:[yeardata sortedArrayUsingDescriptors:sortDescriptors]];
for (NSDictionary * dic in yeardata)
{
NSString * stryear = [dic objectForKey:@"year"];
NSString * strmonth = [dic objectForKey:@"month"];
[year addObject:[NSString stringWithFormat:@"%@ , %@",strmonth,stryear]];
}
i need to sort data is Feb 2017 Mar 2017 June 2017 August 2017 January 2018
Output:
So what's the logic?
You can't do that with a simple
NSSortDescriptor
, because your month is in letter, and "Dec" is before "Oct" alphabetically order speaking, but not in "time" speaking. So you need to create aNSDate
that can be simply compared. You can save that date in the dictionaries of your array if needed, or use asortedArrayUsingComparator:
with a block.To reverse the order, the easiest way in the block:
or
Note: The way of constructing
finalDate1
/finalDate2
might be not optimum.