【问题标题】:Sorting NSArray and NSMutableArray in Objective-C在 Objective-C 中对 NSArray 和 NSMutableArray 进行排序
【发布时间】:2021-05-14 17:59:39
【问题描述】:

我有一个包含 6x 3D 数组和图像像素数据的 NSArray,以及一个包含 6 个值的 NSMutableArray。我想对 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]];

【问题讨论】:

标签: arrays objective-c swift sorting nsarray


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 2016-08-31
    • 2011-10-30
    • 2011-11-29
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    相关资源
    最近更新 更多