gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 06:00:17 26 4
gpt4 key购买 nike

我有一个包含许多 NSArray 的 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]];

最佳答案

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

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

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

关于objective-c - 按值 atIndex 对嵌套的 NSArrays 的 NSMutableArray 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8995390/

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