Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPredicate concatenating attributes

I m trying to figure out how to concatenate attribute names. I have a county and a district attribute that I want to query like

[NSPredicate predicateWithFormat:@"county + district contains[cd] %@",searchBar.text]

gives me unimplemented SQL generation for predicate error. and I am not sure how to implement NSPredicate. Thanks

like image 590
cekisakurek Avatar asked Sep 12 '11 09:09

cekisakurek


3 Answers

This should give you an idea of how to do some more complicated searching. It will match queries for "county district", "district county", etc.

    NSArray *searchTerms = [searchBar.text componentsSeparatedByString:@" "];
    NSString *predicateFormat = @"(county contains[cd] %@) OR (district contains[cd] %@)";
    NSPredicate *predicate;
    if ([searchTerms count] == 1) {
        NSString *term = [searchTerms objectAtIndex:0];
        predicate = [NSPredicate predicateWithFormat:predicateFormat, term, term];
    } else {
        NSMutableArray *subPredicates = [NSMutableArray array];
        for (NSString *term in searchTerms) {
            NSPredicate *p = [NSPredicate predicateWithFormat:predicateFormat, term, term];
            [subPredicates addObject:p];
        }
        predicate = [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates];
    }
    [fetchRequest setPredicate:predicate];

See Cocoa Is My Girlfriend: Adding iTunes-style search to your Core Data application for more explanation.

like image 59
johngraham Avatar answered Nov 15 '22 07:11

johngraham


I ended up implementing another field as concatenating the two variables(district+country) and perform the query on that variable.

like image 39
cekisakurek Avatar answered Nov 15 '22 08:11

cekisakurek


I did something similar and concluded that like cekisakurek, the best method was to concatenate the fields into a common field (more relevant for first/last name)

- (NSString *)fullName {
    return [NSString stringWithFormat:@"%@ %@", self.firstName, self.lastName];
}

and then filtered on this field using 'contains[cd]'

[NSPredicate predicateWithFormat:@"fullName contains[cd] %@", self.searchBar.text];
like image 27
dcwither Avatar answered Nov 15 '22 07:11

dcwither