Question

Hi I create a common set using NSSet's objectsPassingTest method. Is there a way I could write this using an NSPredicate? I want more the test to match on more than just seeing if one set contains an object.

NSSet *commonMusic = [userMusicTitles objectsPassingTest:^BOOL(id obj, BOOL *stop) {
    return [friendMusicTitles containsObject:obj];
}];

The two sets contain NSStrings, and I'd like to use something such as

If userMusicTitles.title LIKE[cd] friendMusicTitles.title

Thanks!

Was it helpful?

Solution

If I get you correctly you want to create a new NSSet that contain all element that are common to 2 different NSSet.

- (void)testTest
{
NSArray *a = @[ @"boris", @"bob", @"claire", @"x" ];
NSArray *b = @[ @"Boris", @"BOB", @"vince", @"y", @"x" ];
NSSet *userMusicTitles = [NSSet setWithArray:a];
NSSet *friendMusicTitles = [NSSet setWithArray:b];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF LIKE[cd] $STR"];
__block NSPredicate *blockPredicate = nil;
NSSet *commonMusic = [userMusicTitles objectsPassingTest:^BOOL(NSString *obj, BOOL *stop) {
    blockPredicate = [predicate predicateWithSubstitutionVariables:@{ @"STR" : obj }];
    return ([friendMusicTitles filteredSetUsingPredicate:blockPredicate].count > 0);
}];

NSLog(@"common music == %@", commonMusic);
}

Other option.

NSMutableSet have the - (void)intersectSet:(NSSet *)otherSet method. But it won't do the LIKE[cd]. You would have to store your NSString already in [cd] form.

Other option would be to loop throughout one set and use the value in a predicate then add the result to a NSMutableSet that at the end would contain your elements.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top