21

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?

2 Answers 2

62

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:@"*"]]]
Sign up to request clarification or add additional context in comments.

3 Comments

Oh man this is even simpler.. I've tried both answers, and they both function equally well!
how can I implement partial search in this? So if the user types "Bask" the Card with the tag "Basketball" shows up?
Right, but does this remove the functionality to search within the keywords array?
9

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

2 Comments

I'm in love with the answer by @Vignesh
I forgive you. I mean it is the first time I have seen ANY used correctly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.