核心数据查询多个列与单个搜索字符串 [英] Core Data Query Multiple Columns with Single Search String

查看:143
本文介绍了核心数据查询多个列与单个搜索字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的核心数据模型,有两个字符串属性(大小和类别)。给定像小小部件这样的搜索字符串可以返回与所有查询词匹配的记录,至少有一个属性(即小大小和小部件类别的所有记录)?我目前有:

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 query words to at least one attribute (i.e. all records with 'small' size and 'widget' category)? I currently have:

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

这不会返回任何结果小部件)。有什么建议么?请注意,搜索字符串将由用户从文本字段输入,并且可能以任何顺序排列,因此我无法手动分割。

This won't return any results (as no category or size equals "small widget"). Any suggestions? Note that the search strings will be user entered from a text field and may come in any order so I can't split up manually.

推荐答案

我没有测试它,但它看起来像你想要的:

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

这篇关于核心数据查询多个列与单个搜索字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆