Merging NSArrays in Objective-C
-
16-09-2019 - |
Question
I have an NSDictionary where each key points to an array. I later want to merge all of the values into one array. Is there a way to use the API to do something more efficient than say:
NSArray *anArray = [someDictionary allValues];
NSMutableArray *newArray = [NSMutableArray array];
start outter loop on anArray
start inner loop on objects in anArray
add objectAtIndex to newArray
Solution
Just use [newArray addObjectsFromArray:anArray];
OTHER TIPS
There is some confusion in Benn Gottlieb's answer above. To clarify, he is suggesting using addObjectsFromArray instead of the inner loop, whereas Coocoo is confused because he thinks it is being suggested as a replacement for ALL the looping. (If you do this, you will indeed be left with an unflattened array of arrays as per his objection.)
Here is a reasonably elegant solution that doesn't require any explicit looping:
NSArray *anArray = [someDictionary allValues];
NSArray *flattenedArray = [anArray valueForKeyPath: @"@unionOfArrays.self"];
btw this code will leave duplicates in the flattened array. If you want to remove duplicates, use distinctUnionOfArrays instead of unionOfArrays.