我有一个自定义对象,其中包含基于时间段的信息,例如属性 endCalYear、endMonth 和 periodLength,它们指示每个时间段的结束及其长度。
我想创建一个NSSortDescriptor
基于或其他排序方法,结合了这三个属性并允许同时在所有三个键上对该对象进行排序。
Example:
EndCalYear endMonth periodLength (months) sortOrder
2012 6 6 1
2012 6 3 2
2012 3 3 3
2011 12 12 4
排序算法将完全根据我自己的算法自行决定。
我如何编写这样的算法?
基于块的sortDescriptorWithKey:ascending:comparator:
在我看来,这种方法不起作用,因为它只允许我指定一个排序键。但是,我需要同时对所有三个键进行排序。
关于如何解决这个问题有什么想法或想法吗?
谢谢你!
你可以用块来排序:
NSArray *sortedArray;
sortedArray = [myArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
MyObject *first = (MyObject*)a;
MyObject *second = (MyObject*)b;
if (first.endCalYear < second.endCalYear) {
return NSOrderedAscending;
}
else if (first.endCalYear > second.endCalYear) {
return NSOrderedDescending;
}
// endCalYear is the same
if (first.endMonth < second.endMonth) {
return NSOrderedAscending;
}
else if (first.endMonth > second.endMonth) {
return NSOrderedDescending;
}
// endMonth is the same
if (first.periodLength < second.periodLength) {
return NSOrderedAscending;
}
else if (first.periodLength > second.periodLength) {
return NSOrderedDescending;
}
// periodLength is the same
return NSOrderedSame;
}]
这排序依据endCalYear
上升,那么endMonth
上升并最终periodLength
上升。您可以修改它以更改顺序或切换 if 语句中的符号以使其降序。
对于 NSFetchedResultsController 你可能想尝试其他方法:
看起来你可以传递一个描述符列表 http://developer.apple.com/library/ios/#documentation/CoreData/Reference/NSFetchedResultsController_Class/Reference/Reference.html,您想要排序的每一列一个:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSSortDescriptor *descriptor1 = [[NSSortDescriptor alloc] initWithKey:@"endCalYear" ascending:YES];
NSSortDescriptor *descriptor2 = [[NSSortDescriptor alloc] initWithKey:@"endMonth" ascending:YES];
NSSortDescriptor *descriptor3 = [[NSSortDescriptor alloc] initWithKey:@"periodLength" ascending:YES];
NSArray *sortDescriptors = @[descriptor1, descriptor2, descriptor3];
[fetchRequest setSortDescriptors:sortDescriptors];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)