Order two NSMutableArrays based on one

2019-01-12 01:44发布

问题:

I have two NSMutableArrays. The content of the first is numerically, which is paired to the content of the second one:

First Array    Second Array
   45              Test45
   3               Test3
   1               Test1
   10              Test10
   20              Test20

That's the look of both arrays. Now how could I order them so numerically so they end up like:

First Array    Second Array
   1               Test1
   3               Test3
   10              Test10
   20              Test20
   45              Test45

Thanks!

回答1:

I would put the two arrays into a dictionary as keys and values. Then you can sort the first array (acting as keys in the dictionary) and quickly access the dictionary's values in the same order. Note that this will only work if the objects in the first array support NSCopying because that's how NSDictionary works.

The following code should do it. It's actually quite short because NSDictionary offers some nice convenience methods.

// Put the two arrays into a dictionary as keys and values
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:secondArray forKeys:firstArray];
// Sort the first array
NSArray *sortedFirstArray = [[dictionary allKeys] sortedArrayUsingSelector:@selector(compare:)];
// Sort the second array based on the sorted first array
NSArray *sortedSecondArray = [dictionary objectsForKeys:sortedFirstArray notFoundMarker:[NSNull null]];


回答2:

Rather than keep two parallel arrays, I'd keep a single array of model objects. Each number from the first array would be the value of one property, and each string from the second array would be the value of the other property. You could then sort on either or both properties using sort descriptors.

Generally, in Cocoa and Cocoa Touch, parallel arrays make work while model objects save work. Prefer the latter over the former wherever you can.