【发布时间】:2016-03-06 15:20:35
【问题描述】:
我有一个NSDictionary 对象数组,每个对象都有一个EventDate 和SecurityLevel。我想先按日期排序,然后按安全级别排序。我该怎么做?
Obj1: SecurityLevel: 5, Date: 20/05/2015 22:03
Obj2: SecurityLevel: 5, Date: 05/03/2015 05:28
Obj3: SecurityLevel: 4, Date: 14/04/2015 11:01
Obj4: SecurityLevel: 4, Date: 07/08/2015 09:31
Obj6: SecurityLevel: 3, Date: 24/04/2015 21:06
Obj5: SecurityLevel: 3, Date: 29/01/2016 22:38
Obj7: SecurityLevel: 2, Date: 02/06/2015 20:49
Obj8: SecurityLevel: 2, Date: 13/07/2015 17:46
Obj9: SecurityLevel: 1, Date: 19/08/2015 07:57
它们应该这样排序:
Obj1: SecurityLevel: 5, Date: 20/05/2015 22:03
Obj2: SecurityLevel: 5, Date: 05/03/2015 05:28
Obj4: SecurityLevel: 4, Date: 07/08/2015 09:31
Obj3: SecurityLevel: 4, Date: 14/04/2015 11:01
Obj5: SecurityLevel: 3, Date: 29/01/2016 22:38
Obj6: SecurityLevel: 3, Date: 24/04/2015 21:06
Obj8: SecurityLevel: 2, Date: 13/07/2015 17:46
Obj7: SecurityLevel: 2, Date: 02/06/2015 20:49
Obj9: SecurityLevel: 1, Date: 19/08/2015 07:57
我做了类似的事情,但它没有按预期工作:
- (NSArray*)sortEventsByDateAndSecurity:(NSArray*)toSort
{
NSSortDescriptor *securityDescriptor = [[NSSortDescriptor alloc] initWithKey:@"SeverityLevel" ascending:NO];
NSArray *sortDescriptors = @[securityDescriptor];
NSArray *sortedSecurity = [toSort sortedArrayUsingDescriptors:sortDescriptors];
NSArray *reverseOrderUsingComparator = [sortedSecurity sortedArrayUsingComparator:^(id obj1, id obj2) {
NSDictionary *dictObject1 = (NSDictionary*)obj1;
NSDictionary *dictObject2 = (NSDictionary*)obj2;
NSDate *obj1Date = [Utils stringToDate:[dictObject1 valueForKey:@"EventDate"] format:@"dd/MM/yyyy HH:mm"];
NSDate *obj2Date = [Utils stringToDate:[dictObject2 valueForKey:@"EventDate"] format:@"dd/MM/yyyy HH:mm"];
return [obj1Date compare:obj2Date];
}];
return reverseOrderUsingComparator;
}
【问题讨论】:
-
为什么将日期保存为字符串?将它们导入应用程序后立即将它们转换为
NSDate对象会更有效(且有用)。 -
好的,假设我将它们转换为 NSDate 对象,如何根据需要对对象进行排序?
-
不知道。只是关于使用正确的类型来表示您的数据的评论。
标签: ios objective-c arrays sorting nsdate