gpt4 book ai didi

ios - 使用 2 个排序描述符对数组进行排序

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:07:51 26 4
gpt4 key购买 nike

我有一个 NSDictionary 对象数组,每个对象都有一个 EventDateSecurityLevel。我想先按日期对它们进行排序,然后再按安全级别对它们进行排序。我该怎么做?

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;
}

最佳答案

您应该简单地调用 sortedArrayUsingDescriptors: 并使用 2 个而不是 1 个描述符的数组:

- (NSArray*)sortEventsByDateAndSecurity:(NSArray*)toSort
{
NSSortDescriptor *securityDescriptor = [[NSSortDescriptor alloc] initWithKey:@"SeverityLevel" ascending:NO];
NSSortDescriptor *eventDateDescriptor = [[NSSortDescriptor alloc] initWithKey:@"EventDate" ascending:NO comparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
NSDate *obj1Date = [Utils stringToDate:obj1 format:@"dd/MM/yyyy HH:mm"];
NSDate *obj2Date = [Utils stringToDate:obj2 format:@"dd/MM/yyyy HH:mm"];
return [obj1Date compare:obj2Date];
}];
NSArray *sortDescriptors = @[securityDescriptor, eventDateDescriptor];
return [toSort sortedArrayUsingDescriptors:sortDescriptors];
}

在这种情况下,第二个排序描述符将仅应用于在第一个排序描述符方面相等的对象。对于您的情况,这意味着具有相同 SecurityLevel 的对象将按 EventDate 排序。

关于ios - 使用 2 个排序描述符对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35828656/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com