Core Data Query Multiple Columns with Single Search String

后端 未结 2 1036
长发绾君心
长发绾君心 2021-01-22 11:21

I have a simple Core Data model with two string attributes (size and category). Given a search string like \'small widget\' is it possible to return records that match all the q

2条回答
  •  清酒与你
    2021-01-22 11:48

    I haven't tested it but it looks like your want this:

    NSString *search = @"small widget";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@ contains[cd] size AND %@ contains[cd] category", search, search];
    

    The search string would contain (or not) the size and the category, you should ask if the current size or category is contained on the search string.

    You could also split the search string and modify your predicate. You should them to identify the one that performs better

    NSString *search = @"small widget";
        NSArray *array = [search componentsSeparatedByString:@" "];
        NSMutableArray *subPredicates = [NSMutableArray array];
        for (NSString *q in array) {
            [subPredicates addObject:
             [NSPredicate predicateWithFormat:@"size contains[cd] %@ OR category contains[cd] %@", q, q]];
        }
        NSCompoundPredicate *predicate = [[[NSCompoundPredicate alloc] initWithType:NSAndPredicateType
                                                                     subpredicates:subPredicates] autorelease];
    

提交回复
热议问题