0

I have an NSArray containing 6x 3D arrays with image pixel data, and an NSMutableArray with 6 values. I would like to sort the NSMutableArray array numerically and sort the NSArray in the same order that the NSMutableArray is sorted. I know how to do this in python but I am not great with Objective-C

i.e.,: from: NSArray = [img1, img2, img3] NSMutableArray = [5, 1, 9] to: 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]];
user3470496
  • 141
  • 7
  • 33
  • hi perhaps a custom comparison method https://stackoverflow.com/questions/805547/how-do-i-sort-an-nsmutablearray-with-custom-objects-in-it – IronMan Feb 11 '21 at 00:43
  • Does this answer your question? [Sorting two NSArrays together side by side](https://stackoverflow.com/questions/12436927/sorting-two-nsarrays-together-side-by-side) – Willeke Feb 11 '21 at 07:11
  • Side note: If `img1` is linked to value `5`, it might be better to use a `NSDictionary` (or custom `Class`) and an array of them instead. That would avoid you that each time the order is changed, an element is changed to reflect the action on the second array. – Larme Feb 11 '21 at 08:57

1 Answers1

1

Likely you use the wrong data structure from the very beginning. You shouldn't come up with key-value pairs in different arrays. However, …

First create a dictionary to pair the two lists, then sort the keys, finally retrieve the values:

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]];
}
Amin Negm-Awad
  • 16,582
  • 3
  • 35
  • 50