Friday, June 21, 2013

NSMutableSet unionSet example in Objective C (iOS).


NSMutableSet unionSet

Adds each object in another given set to the receiving set, if not present.

- (void)unionSet:(NSSet *)otherSet

Parameters of [NSMutableSet unionSet]
otherSet
The set of objects to add to the receiving set.

NSMutableSet unionSet example.
NSArray *symbols = [NSArray arrayWithObjects:@"AAPL",@"GOOG",@"INTC",@"YHOO",nil];

NSArray *fetchedSymbols = [NSArray arrayWithObjects:@"AMD",@"BIDU",@"GOOG",@"GMCR",@"INTC",@"YHOO",nil];

NSMutableSet* localSet = [[NSMutableSet alloc] initWithArray:symbols];
NSMutableSet* serverSet = [[NSMutableSet alloc] initWithArray:fetchedSymbols];

[localSet unionSet:serverSet];

for (id symbol in localSet) {
    NSLog(@"%@",symbol);
}

Example of [NSMutableSet unionSet].
By using NSSet, as others have pointed out. For

NSArray * a = [NSArray arrayWithObjects: ... ];
NSArray * b = [NSArray arratWithObjects: ... ];
NSMutableSet * set = [NSMutableSet setWithArray:a];
[set intersectSet:[NSSet setWithArray:b];
[set unionSet:[NSSet setWithArray:b];

NSMutableSet unionSet example.
NSMutableArray *first=[NSMutableArray arrayWithArray:@[@"1",@"2",@"3",@"4",@"5",@"6"]];
NSMutableArray *second=[NSMutableArray arrayWithArray:@[@"2",@"4",@"6",@"8",@"0",@"12"]];

NSMutableSet *firstSet  = [NSMutableSet setWithArray:first];
NSMutableSet *secondSet = [NSMutableSet setWithArray:second];
[firstSet unionSet:secondSet];
NSArray *uniqueArray    = [firstSet allObjects];

End of NSMutableSet unionSet example article.