按日期的 2 个属性对对象数组进行排序
Sorting array of objects by 2 attributes of date
我有一个 NSArray
个 CoreData
个对象,里面有两个属性:月和年。我想按年然后按月对数组进行排序。
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
我该怎么做?
// 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...
我有一个 NSArray
个 CoreData
个对象,里面有两个属性:月和年。我想按年然后按月对数组进行排序。
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
我该怎么做?
// 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...