按值atIndex对嵌套NSArrays的NSMutableArray进行排序

时间:2012-01-24 22:45:47

标签: objective-c nsmutablearray nsarray

我有一个包含许多NSArrays的NSMutableArray。在每个NSArray中的特定(静态)索引是我想要对NSMutableArray进行排序的值(从降序/最大到最小)。现在我尝试使用NSSortDescriptor,但无法通过KVC来获取和比较我特定索引的值。详细说明:

#define INDEX_OF_DESIRED_STRING 2

NSArray *a1 = [NSArray arrayWithObjects:@"test", @"jjj", @"3454", nil]; 
NSArray *a2 = [NSArray arrayWithObjects:@"test1", @"jjj", @"12", nil]; 
NSArray *a3 = [NSArray arrayWithObjects:@"test2", @"jjj", @"232333", nil]; 
NSArray *a4 = [NSArray arrayWithObjects:@"test3", @"jjj", @".122", nil]; 

NSMutableArray *mutableA = [[NSMutableArray alloc] initWithObjects:a1, a2, a3, a4, nil]; 

// Then I'd sort with something like this... although this of course
// does not take the arrays into account. Sorts as if it were only made of strings

NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"floatValue"
                                                 ascending:NO];

[mutableA sortUsingDescriptors:[NSArray arrayWithObject:sd]]; 

1 个答案:

答案 0 :(得分:3)

尝试使用比较器块进行排序:

NSArray *a1 = [NSArray arrayWithObjects:@"test", @"jjj", @"3454", nil]; 
NSArray *a2 = [NSArray arrayWithObjects:@"test1", @"jjj", @"12", nil]; 
NSArray *a3 = [NSArray arrayWithObjects:@"test2", @"jjj", @"232333", nil]; 
NSArray *a4 = [NSArray arrayWithObjects:@"test3", @"jjj", @".122", nil]; 

NSMutableArray *mutableA = [[NSMutableArray alloc] initWithObjects:a1, a2, a3, a4, nil];

NSLog(@"mutableA before sorting: %@", mutableA);

[mutableA sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSArray *array1 = (NSArray *)obj1;
    NSArray *array2 = (NSArray *)obj2;
    NSString *num1String = [array1 objectAtIndex:INDEX_OF_DESIRED_STRING];
    NSString *num2String = [array2 objectAtIndex:INDEX_OF_DESIRED_STRING];

    return [num1String compare:num2String];
}];

NSLog(@"mutableA after sorting: %@", mutableA);

比较器块比它可能更冗长,但我希望它能清楚地知道发生了什么。