Friday, June 21, 2013

NSMutableSet addObjectsFromArray example in Objective C (iOS).


NSMutableSet addObjectsFromArray

Adds to the set each object contained in a given array that is not already a member.

- (void)addObjectsFromArray:(NSArray *)array

Parameters of [NSMutableSet addObjectsFromArray]
array
An array of objects to add to the set.

NSMutableSet addObjectsFromArray example.
NSMutableSet *randomCards = [NSMutableSet setWithCapacity:10];

[randomCards addObjectsFromArray:whiteListArray];

while ([randomCards count] < 10) {
    NSNumber *randomNumber = [NSNumber numberWithInt:(arc4random() % [randoms count])];
    [randomCards addObject:[randoms objectAtIndex:[randomNumber intValue]]];
}

Example of [NSMutableSet addObjectsFromArray].
If you are using NSSet you have to create a new NSMutableSet, which has the method intersectSet:, which can be used for your purpose:

NSMutableSet *set1 = [[NSMutableSet alloc] initWithObjects:@"0", @"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", nil];
NSMutableSet *set2 = [[NSMutableSet alloc] initWithObjects:@"2", @"4", @"6", @"8", @"10", @"12", @"14", @"18", nil];

NSLog(@"set1: %@", set1);
NSLog(@"set2: %@", set2);
[set1 intersectSet:set2];
NSLog(@"isec: %@", set1);
You can create a NSMutableSet from an NSArray using the addObjectsFromArray: method:

NSArray *array = [[NSArray alloc] initWithObjects:@"1", @"2", nil];
NSMutableSet *set = [[NSMutableSet alloc] init];
[set addObjectsFromArray:array];

NSMutableSet addObjectsFromArray example.
NSMutableArray *firstArray = [NSMutableArray arrayWithObjects:@"Bill", @"Ben", @"Chris", @"Melissa", nil];
NSMutableArray *secondArray = [NSMutableArray arrayWithObjects:@"Bill", @"Paul" nil];

NSSet *firstSet = [NSSet setWithArray:firstArray];
NSMutableSet *secondSet = [NSMutableSet setWithCapacity:[secondArray count]];
[secondSet addObjectsFromArray:secondArray];

NSSet *result = [secondSet minusSet:firstSet];

End of NSMutableSet addObjectsFromArray example article.