Order two NSMutableArrays based on one

前端 未结 2 381
庸人自扰
庸人自扰 2020-12-03 16:19

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              


        
相关标签:
2条回答
  • 2020-12-03 16:43

    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.

    0 讨论(0)
  • 2020-12-03 16:46

    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]];
    
    0 讨论(0)
提交回复
热议问题