在 Objective-C 中对 NSArray 和 NSMutableArray 进行排序

Sorting NSArray and NSMutableArray in Objective-C

我有一个 NSArray 包含 6x 3D 数组和图像像素数据,还有一个 NSMutableArray 有 6 个值。我想对 NSMutableArray 数组进行数字排序,并按照与 NSMutableArray 排序相同的顺序对 NSArray 进行排序。我知道如何在 python 中执行此操作,但我不擅长 Objective-C

即: 从: NSArray = [img1, img2, img3] NSMutableArray = [5, 1, 9] 到: NSArray = [img2, img1, img3] NSMutableArray = [1, 5, 9]

NSArray *imageArray = [...some images];

NSMutableArray *valueList = [[NSMutableArray alloc] initWithCapacity:0];

float value1 = 5.0;
float value2 = 1.0;
float value3 = 9.0;

[valueList addObject:[NSDecimalNumber numberWithFloat:value1]];

[valueList addObject:[NSDecimalNumber numberWithFloat:value2]];

[valueList addObject:[NSDecimalNumber numberWithFloat:value3]];

很可能你从一开始就使用了错误的数据结构。您不应该在不同的数组中提出键值对。然而,...

首先创建一个字典来对两个列表进行配对,然后对键进行排序,最后检索值:

NSArray *numbers = …; // for sorting
NSArray *images = …;  // content

// Build pairs
NSDictionary *pairs = [NSDictionary dictionaryWithObjects:images forKeys:numbers];

// Sort the index array
numbers = [numbers sortedArrayByWhatever]; // select a sorting method that's comfortable for you

// Run through the sorted array and get the corresponding value
NSMutableArray *sortedImages = [NSMutableArray new];
for( id key in numbers )
{
   [sortedImages appendObject:pairs[key]];
}