Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NSPredicate to search an array with an array

Tags:

I have an array of Card objects (NSObjects), each with a field called tags, which is an NSArray of NSStrings.

I would then like to split up the user's search term into an array called keywords of strings by componentsSeparatedByString, then use NSPredicate to filter my array of Cards based on which elements have tags containing at least 1 keyword in keywords.

I hope that's not too convoluted! I've tried using the NSPredicate IN clause to no avail. How should I do this?

like image 627
quantum Avatar asked Jul 02 '12 11:07

quantum


2 Answers

Considering array contains card Object.

 NSArray *keyWordsList = [keywords componentSeparatedByString:@","];
 [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"ANY %K IN %@",@"tags",keyWordsList]]

EDIT:

To search partially you can use LIKE operator.

[array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"ANY %K LIKE[cd] %@",@"tags",[partialkeyWord stringByAppendingString:@"*"]]]
like image 159
Vignesh Avatar answered Oct 18 '22 17:10

Vignesh


Don't kill me if this isn't exactly right, but something like this will work.

NSArray* arrayOfCards = [NSArray array];
NSArray* keywords = [NSArray array];
NSPredicate* containsAKeyword = [NSPredicate predicateWithBlock: ^BOOL(id evaluatedObject, NSDictionary *bindings) {
    Card* card = (Card*)evaluatedObject;
    NSArray* tagArray = card.tags;
    for(NSString* tag in tagArray) {
       if( [keywords containsObject: tag] ) 
          return YES;
    }

    return NO;
}];

NSArray* result = [arrayOfCards filteredArrayUsingPredicate: containsAKeyword];
like image 41
Paul de Lange Avatar answered Oct 18 '22 18:10

Paul de Lange