views:

35

answers:

1

Hi the problem goes like this:

I have in CoreData entities that have a title and a relationship to keywords entities.

I need a predicate that helps me to fetch all those entities whose title contains the keywords I type. I have the code below that should do this but it doesn't:

NSArray *keywords = [searchString componentsSeparatedByString:@" "];
NSString *predicateString = @"";
for(NSInteger i = 0; i < [keywords count]; i++) {
    if(((NSString*)[keywords objectAtIndex:i]).length != 0) {
        if(i==0) {
            predicateString = [keywords objectAtIndex:i];
        }
        else {
            predicateString = [predicateString stringByAppendingFormat:@" and keywords.normalizedKeyword contains[cd] %@", [keywords objectAtIndex:i]]; 
        }

    }
}

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"keywords.normalizedKeyword contains[cd] %@",predicateString];

For example I have entities with titles like this:

1) "Great Coloring theme" 2) "Theme for kids" 3) "Cars for kids"

my keywords db will contain:

great coloring theme for kids cars

How can I create a predicate so when I type for example:

Theme for

the result will be 2) and 3)

or if I type:

great theme

the result will be 1) and 2)

Any help in getting the right predicate to achieve this is very much appreciated. What I tried to do there it doesn't work and I am out of ideas.

Thanks!

+2  A: 

I have found the answer myself. To solve such a problem you have to use a NSCompoundPredicate. The solution to my problem was this:

    NSArray *keywords = [lowerBound componentsSeparatedByString:@" "];
NSMutableArray *predicates = nil;
for(NSInteger i = 0; i < [keywords count]; i++) {
    if(((NSString*)[keywords objectAtIndex:i]).length != 0) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"keywords.normalizedKeyword contains[cd] %@", [keywords objectAtIndex:i]];
        if(predicates == nil) {
            predicates = [[NSMutableArray alloc] initWithCapacity:0];
        }

        [predicates addObject:predicate];
    }
}

NSPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:predicates];
Horatiu Paraschiv