Question

I want to sort objects with different descriptors keys).

The problem:

I have two arrays with populated with objects of different classes. and The two classes do not share a common attribute to use as a sort descriptor.

I want to sort the arrays alphabetically, and return only one array containing all the objects.

  • Array1 = with objects [A Class]
    • sorted by "name"
  • Array2 = with objects [B Class]
    • sorted by "title"

FinalArray => sort (again) alphabetically with all object's of Array's (1,2)

Was it helpful?

Solution

You can do it like this:

  • Create NSArray *result with the size of the combined arrays
  • Concatenate the two arrays into the result array by copying the elements of the first array followed by the elements of the second array into the result.
  • Use sortedArrayUsingComparator: with a comparator that "understands" both types.

Here is a skeletal implementation:

NSArray *sortedArray = [result sortedArrayUsingComparator: ^(id obj1, id obj2) {
    NSString *key1, *key2;
    if ([obj1 isKindOfClass:['class has a title' class]]) {
         key1 = [obj1 title];
    } else { // It's the kind of objects that has a name
        key1 = [obj1 name];
    }
    if ([obj2 isKindOfClass:['class has a title' class]]) {
         key2 = [obj2 title];
    } else { // It's the kind of objects that has a name
        key2 = [obj2 name];
    }
    // Do the comparison
    return [key1 caseInsensitiveCompare:key2];
}];

OTHER TIPS

One possible solution: add all array objects to an NSMutableDictionary, where the key is "name" or "title" as appropriate, then pull all of the dictionary keys, sort them, and retrieve by sorted key the objects into a new array:

NSMutableDictionary* dict = [NSMutableDictionary dictionary];
for (a in array1) {
    [dict setObject:a forKey:a.name];  // assumes name is property
}
for (b in array2) {
    [dict setObject:b forKey:b.title]; // assumes title is property
}
NSArray* sortedKeys = [[dict allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
NSArray* objects = [dict objectsForKeys:sortedKeys notFoundMarker:[NSNull null]];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top