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]];
3
  • hi perhaps a custom comparison method stackoverflow.com/questions/805547/… Commented Feb 11, 2021 at 0:43
  • Does this answer your question? Sorting two NSArrays together side by side Commented Feb 11, 2021 at 7: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. Commented Feb 11, 2021 at 8:57

1 Answer 1

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]];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.