Showing posts with label NSMutableSet. Show all posts
Showing posts with label NSMutableSet. Show all posts

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.

NSMutableSet minusSet example in Objective C (iOS).


NSMutableSet minusSet

Removes each object in another given set from the receiving set, if present.

- (void)minusSet:(NSSet *)otherSet

Parameters of [NSMutableSet minusSet]
otherSet
The set of objects to remove from the receiving set.

NSMutableSet minusSet example.
If duplicate items are not significant in the arrays, you can use the minusSet: operation of NSMutableSet:

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];

Example of [NSMutableSet minusSet].
NSMutableSet *countriesSet = [NSMutableSet setWithArray:countriesArray];
NSSet *unSet = [NSSet setWithArray:unCountriesArray];
[countriesSet minusSet:unSet];
// countriesSet now contains only those countries who are not part of unSet

NSMutableSet minusSet example.
The your code could be:

NSMutableSet *web = [[NSMutableSet alloc] initWithObjects:@"2",@"3",@"4",nil];
NSMutableSet *disk = [[NSMutableSet alloc] initWithObjects:@"1",@"2",@"3",nil];

NSMutableSet * remArray = [[NSMutableSet setWithSet:disk] minusSet:web];
NSMutableSet * addArray = [[NSMutableSet setWithSet:web] minusSet:disk];
You can also read the Collections Programming Topics guide. Before using an array you have to determine if you want an ordered collection or not.

End of NSMutableSet minusSet example article.

NSMutableSet intersectSet example in Objective C (iOS).


NSMutableSet intersectSet

Removes from the receiving set each object that isn’t a member of another given set.

- (void)intersectSet:(NSSet *)otherSet

Parameters of [NSMutableSet intersectSet]
otherSet
The set with which to perform the intersection.

NSMutableSet intersectSet example.
Use NSMutableSet:

NSMutableSet *intersection = [NSMutableSet setWithArray:array1];
[intersection intersectSet:[NSSet setWithArray:array2]];
[intersection intersectSet:[NSSet setWithArray:array3]];

NSArray *array4 = [intersection allObjects];

Example of [NSMutableSet intersectSet].
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 intersectSet example.
Something like this?

NSMutableSet* set1 = [NSMutableSet setWithArray:array1];
NSMutableSet* set2 = [NSMutableSet setWithArray:array2];
[set1 intersectSet:set2]; //this will give you only the obejcts that are in both sets

NSArray* result = [set1 allObjects];
This has the benefit of not looking up the objects in the array, while looping through another array, which has N^2 complexity and may take a while if the arrays are large.

Edit: set2 doesn't have to be mutable, might as well use just

NSSet* set2 = [NSSet setWithArray:array2];

End of NSMutableSet intersectSet example article.

NSMutableSet initWithCapacity example in Objective C (iOS).


NSMutableSet initWithCapacity

Returns an initialized mutable set with a given initial capacity.

- (id)initWithCapacity:(NSUInteger)numItems

Parameters
numItems
The initial capacity of the set.

Return Value of [NSMutableSet initWithCapacity]
An initialized mutable set with initial capacity to hold numItems members. The returned set might be different than the original receiver.

Discussion of [NSMutableSet initWithCapacity]
Mutable sets allocate additional memory as needed, so numItems simply establishes the object’s initial capacity.

NSMutableSet initWithCapacity example.
You probably want

NSMutableSet *set = [[NSMutableSet alloc] initWithCapacity: someNumber];
or

NSMutableSet *set = [NSMutableSet setWithCapacity: someNumber];

Example of [NSMutableSet initWithCapacity].
NSSet* tom = [[NSMutableSet alloc] initWithCapacity:1];
NSSet* dick = [[NSMutableSet alloc] initWithCapacity:1];
NSSet* harry = [tom setByAddingObjectsFromSet:dick];

printf("tom   retainCount: %d \n", [tom retainCount]);
printf("dick  retainCount: %d \n", [dick retainCount]);
printf("harry retainCount: %d \n", [harry retainCount]);

NSMutableSet initWithCapacity example.
NSMutableSet* collectibleCopy = [[NSMutableSet alloc] initWithCapacity: [_collectibles count]];
for ( id thing in _collectibles ) {
    [collectibleCopy addObject: thing];
}

End of NSMutableSet initWithCapacity example article.

NSMutableSet filterUsingPredicate example in Objective C (iOS).


NSMutableSet filterUsingPredicate

Evaluates a given predicate against the set’s content and removes from the set those objects for which the predicate returns false.

- (void)filterUsingPredicate:(NSPredicate *)predicate

Parameters
predicate
A predicate.

Discussion of [NSMutableSet filterUsingPredicate]
The following example illustrates the use of this method.

NSMutableSet filterUsingPredicate example.
NSMutableSet *mutableSet =
    [NSMutableSet setWithObjects:@"One", @"Two", @"Three", @"Four", nil];
NSPredicate *predicate =
    [NSPredicate predicateWithFormat:@"SELF beginswith 'T'"];
[mutableSet filterUsingPredicate:predicate];
// mutableSet contains (Two, Three)

Example of [NSMutableSet filterUsingPredicate].
If the strings inside the array are known to be distinct, you can use sets. NSSet is faster then NSArray on large inputs:

NSArray * inputArray = [NSMutableArray arrayWithObjects:@"one", @"two", @"one again", nil];

NSMutableSet * matches = [NSMutableSet setWithArray:inputArray];
[matches filterUsingPredicate:[NSPredicate predicateWithFormat:@"SELF contains[c] 'one'"]];

NSMutableSet * notmatches = [NSMutableSet setWithArray:inputArray];
[notmatches  minusSet:matches];

NSMutableSet filterUsingPredicate example.
 - (void)didSaveNotficiation:(NSNotification*)notification
    {
            NSSet *objects = nil;
            NSMutableSet *combinedSet = nil;
            NSPredicate *predicate = nil;

            NSDictionary *userInfo = [notification userInfo];

            objects = [userInfo objectForKey:NSInsertedObjectsKey];
            combinedSet = [NSMutableSet setWithSet:objects];

            objects = [[notification userInfo] objectForKey:NSUpdatedObjectsKey];
            [combinedSet unionSet:objects];

            objects = [[notification userInfo] objectForKey:NSDeletedObjectsKey];
            [combinedSet unionSet:objects];

//THis is slow
            predicate = [NSPredicate predicateWithFormat:@"entity.name == %@ && %K == %@",
                                                         [XXContact entityName], XXContactRelationship.user,self];
            [combinedSet filterUsingPredicate:predicate];

            if ([combinedSet count] == 0) {
                return;
            }

            [self process];

/* This is much faster
            [combinedSet enumerateObjectsUsingBlock:^(id obj, BOOL *stop) {
                if ([obj isKindOfClass:[XXContact class]]) {
                    XXContact* contact = (XXContact*)obj;
                    if (contact.user == self) {
                        [self process];
                        *stop = YES;
                    }
                }
            }];
*/
}

End of NSMutableSet filterUsingPredicate example article.

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.

NSMutableSet addObject example in Objective C (iOS).


NSMutableSet addObject

Adds a given object to the set, if it is not already a member.

- (void)addObject:(id)object

Parameters of [NSMutableSet addObject]
object
The object to add to the set.

NSMutableSet addObject example.
- (void)applicationDidFinishLaunching:(UIApplication *)application {   
    NSSet *s=[NSSet setWithObject:@"setWithObject"];
    NSMutableSet *m=[NSMutableSet setWithCapacity:1];
    [m addObject:@"Added String"];
    NSMutableSet *n = [[NSMutableSet alloc] initWithCapacity:1];
    [self showSuperClasses:s];
    [self showSuperClasses:m];
    [self showSuperClasses:n];
    [self showSuperClasses:@"Steve"];  
}

- (void) showSuperClasses:(id) anObject{
    Class cl = [anObject class];
    NSString *classDescription = [cl description];
    while ([cl superclass])
    {
        cl = [cl superclass];
        classDescription = [classDescription stringByAppendingFormat:@":%@", [cl description]];
    }
    NSLog(@"%@ classes=%@",[anObject class], classDescription);
}

Example of [NSMutableSet addObject].
At some point before you use the set, you need to create a new NSMutableSet.

To make it easy, you can use something like the following to automatically allocate a new mutable set when you ask to use it for the first time.

- (NSMutableSet *)NHPList {
    if (NHPList == nil) {
        NHPList = [[NSMutableSet alloc] init];
    }
    return NHPList;
}
You would also have to release the memory, usually in your viewDidUnload method by setting NHPList to nil.

If this is the only place that you set the data, you could also just change this line:

[NHPList addObject:[sub name]];
to:

if (self.NHPList == nil) {
    self.NHPList = [[NSMutableSet alloc] init];
}
[self.NHPList addObject:[sub name]];

NSMutableSet addObject example.
+ (NSSet *)variablesInExpression:(id)anExpression
{
NSMutableSet *setOfVariables = [[NSMutableSet alloc] init];
for (NSString *str in anExpression) {
    if ([str hasPrefix:VARIABLE_PREFIX]) {
        [setOfVariables addObject:str];
    }
}
[setOfVariables autorelease];
return setOfVariables;
}

End of NSMutableSet addObject example article.

NSMutableSet setWithCapacity example in Objective C (iOS).


NSMutableSet setWithCapacity

Creates and returns a mutable set with a given initial capacity.

+ (id)setWithCapacity:(NSUInteger)numItems

Parameters of [NSMutableSet setWithCapacity]
numItems
The initial capacity of the new set.

Return Value
A mutable set with initial capacity to hold numItems members.

Discussion of [NSMutableSet setWithCapacity]
Mutable sets allocate additional memory as needed, so numItems simply establishes the object’s initial capacity.

NSMutableSet setWithCapacity example.
-(NSString *) randomizeHint:(NSString *) wordToShuffle{

    NSString * outputstring = @"";

    NSMutableSet * usedNumberSet = [NSMutableSet setWithCapacity:[wordToShuffle length]];

    for (int i=0; i<[wordToShuffle length]; i++) {
        int randomnum = arc4random()%[wordToShuffle length];

        while ([usedNumberSet containsObject:[NSNumber numberWithInt:randomnum]]==YES) {
            randomnum = arc4random()%[wordToShuffle length];
        }

        [usedNumberSet addObject:[NSNumber numberWithInt:randomnum]];

        // just set outputstring like so... no need to worry about a leaky mutable string then
        outputstring = [outputstring stringByAppendingFormat:@"%c",
                    [wordToShuffle characterAtIndex:randomnum]];
    }

    return outputstring;

}

Example of [NSMutableSet setWithCapacity].
You probably want

NSMutableSet *set = [[NSMutableSet alloc] initWithCapacity: someNumber];
or

NSMutableSet *set = [NSMutableSet setWithCapacity: someNumber];

NSMutableSet setWithCapacity 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]]];
}

End of NSMutableSet setWithCapacity example article.