I have an array of NSSet
instances as mentioned in below code.
NSArray *a = @[@"1", @"2", @"3", @"4", @"5"];
NSArray *b = @[@"1", @"2", @"3", @"6", @"7"];
NSArray *c = @[@"1", @"7", @"8", @"9", @"5"];
NSArray *d = @[@"1", @"6", @"7", @"8", @"9"]; ... upto N number of arrays.
These all N arrays are defined in N instances of NSSet
by using [NSSet setWithArray:]
method to create the sets from the arrays. All N instances of sets are stored in one single Array X. Now, I need to perform union set operations for all N sets. How could I achieve this?
There are different ways of doing it. The easiest way is to iterate over the array (of sets) and simply add the new elements to a set.
NSMutableSet *unionSet = [NSMutableSet new];
for( NSSet *singleSet in X) // X is an array of sets as mentioned in the Q
{
[unionSet unionSet:singleSet];
}
However, there is no need to create single intermediate sets before unifying it, because you can add the arrays themselves to the unionSet by using -addObjectsFromArray:
(NSMutableSet
), too.
As a hint I want to mention that in your example (which might differ from the real word), having simply numbers it might by the easier way to use NSIndexSet
and NSMutableIndexSet
from the very beginning.