NSArayはNSSortDescriptorを使って二つのkeyを並べ替えます.
3465 ワード
NSMutableArray *tempArr = [NSMutableArray array];
numMode *num1 = [[numMode alloc] init];
// num1.dict = @{@"key1" : @"123"} ;
[tempArr addObject:num1];
numMode *num2 = [[numMode alloc] init];
num2.firstNum = 3;
num2.dict = @{@"key1" : @"122"} ;
[tempArr addObject:num2];
numMode *num3 = [[numMode alloc] init];
num3.firstNum = 17;
num3.dict = @{@"key1" : @"128"} ;
[tempArr addObject:num3];
numMode *num4 = [[numMode alloc] init];
num4.dict = @{@"key1" : @"0"} ;
num4.firstNum = 9;
[tempArr addObject:num4];
// NSMutableArray *arr =[NSMutableArray arrayWithArray:@[@(1), @(8),@(2),@(19),@(3),@(4),@(5)]];
NSMutableArray *arr = tempArr;
NSSortDescriptor *firstSorter = [[NSSortDescriptor alloc] initWithKey:@"firstNum" ascending:YES];
NSSortDescriptor *secondSorter = [[NSSortDescriptor alloc] initWithKey:@"dict" ascending:YES comparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
NSDictionary *dict1 = obj1;
NSDictionary *dict2 = obj2;
if ([dict1[@"key1"] doubleValue] < [dict2[@"key1"] doubleValue]) {
return NSOrderedDescending;
}
if ([dict1[@"key1"] doubleValue] > [dict2[@"key1"] doubleValue]) {
return NSOrderedAscending;
}
return NSOrderedSame;
}];
[arr sortUsingDescriptors:[NSArray arrayWithObjects: secondSorter,nil]];
for (int i=0; i
NSMutableArray *tempArr = [NSMutableArray array];
numMode *num1 = [[numMode alloc] init];
// num1.dict = @{@"key1" : @"123"} ;
[tempArr addObject:num1];
numMode *num2 = [[numMode alloc] init];
num2.firstNum = 3;
num2.dict = @{@"key1" : @"122"} ;
[tempArr addObject:num2];
numMode *num3 = [[numMode alloc] init];
num3.firstNum = 17;
num3.dict = @{@"key1" : @"128"} ;
[tempArr addObject:num3];
numMode *num4 = [[numMode alloc] init];
num4.dict = @{@"key1" : @"0"} ;
num4.firstNum = 9;
[tempArr addObject:num4];
// NSMutableArray *arr =[NSMutableArray arrayWithArray:@[@(1), @(8),@(2),@(19),@(3),@(4),@(5)]];
NSMutableArray *arr = tempArr;
NSSortDescriptor *firstSorter = [[NSSortDescriptor alloc] initWithKey:@"firstNum" ascending:YES];
NSSortDescriptor *secondSorter = [[NSSortDescriptor alloc] initWithKey:@"dict" ascending:YES comparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
NSDictionary *dict1 = obj1;
NSDictionary *dict2 = obj2;
if ([dict1[@"key1"] doubleValue] < [dict2[@"key1"] doubleValue]) {
return NSOrderedDescending;
}
if ([dict1[@"key1"] doubleValue] > [dict2[@"key1"] doubleValue]) {
return NSOrderedAscending;
}
return NSOrderedSame;
}];
[arr sortUsingDescriptors:[NSArray arrayWithObjects: secondSorter,nil]];
for (int i=0; i