按日期的2个属性对对象数组进行排序

时间:2015-04-26 13:32:13

标签: ios objective-c sorting nsarray

我有NSArrayCoreData个对象,里面有2个属性:月份和年份。我想按年计算数组,然后按月计算。

DbDate 1: month: 04 year: 2010

DbDate 2: month: 04 year: 2012

DbDate 3: month: 06 year: 2011

DbDate 4: month: 05 year: 2015

我想将它们排序在数组中:

DbDate 1 DbDate 3 DbDate 2 DbDate 4

我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

    // If you have an array:
NSArray *arrayOfObject;

NSSortDescriptor *sortByYear = [NSSortDescriptor sortDescriptorWithKey:@"year" ascending:YES];
NSSortDescriptor *sortByMonth = [NSSortDescriptor sortDescriptorWithKey:@"month" ascending:YES];
NSArray *sorts = @[sortByYear, sortByMonth];

NSArray *orderedArray = [arrayOfObject sortedArrayUsingDescriptors:sorts];

// If you want fetch the object ordered, from Core Data.
NSFetchRequest  *yourFetchReques = [[NSFetchRequest alloc] init];
// Set your entity...
[yourFetchReques setSortDescriptors:sorts];
// .... Your code to make the request...