Friday, June 21, 2013

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

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:@" == %@ && %K == %@",
                                                         [XXContact entityName], XXContactRelationship.user,self];
            [combinedSet filterUsingPredicate:predicate];

            if ([combinedSet count] == 0) {

            [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.