user3470496
user3470496

Reputation: 171

Sorting NSArray and NSMutableArray in Objective-C

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

Upvotes: 0

Views: 78

Answers (1)

Amin Negm-Awad
Amin Negm-Awad

Reputation: 16650

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

Upvotes: 1

Related Questions