为 'CONTAINED_BY' 编写 NSPredicate;文本查询 [英] Writing an NSPredicate for 'CONTAINED_BY' text query

查看:39
本文介绍了为 'CONTAINED_BY' 编写 NSPredicate;文本查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个核心数据存储的查询,当实体的属性值出现在更长的字符串中时,它会检索它们;

I am trying to construct a query of a Core Data store which retrieves an entity's attribute values when they occur in longer string;

即,而不是寻找属性值包含一个(较短的)字符串的实例:

i.e, instead of seeking instances where attribute value contains a (shorter) string :

request.predicate = [NSPredicate predicateWithFormat:@"carBrand contains[c] 'merced'"] 

我想找到其属性值'包含在'任意(更长)字符串中的(实体的)实例:

I want to find instances (of the entity) whose attribute values are found 'contained in' an arbitrary (longer) string :

NSString* textString = @"Elaine used to drive Audis, but now owns a Mercedes";
request.predicate = [NSPredicate predicateWithFormat:@"%@ contains[c] carBrand", textString ];

(即检索包含 carBrand = @"Audi" 和 carBrand = @"Mercedes" 的对象的数组)

(ie. retrieve array holding objects with carBrand = @"Audi" and carBrand = @"Mercedes")

在我的尝试中,NSPredicate 似乎不喜欢右侧带有属性名称的表达式并抛出错误...

In my attempts, NSPredicate doesn't seem to like expressions with the attribute name on the right hand side and throws an error...

[__NSCFConstantString countByEnumatingWithState:objects:count:]:无法识别的选择器发送到实例 0x

[__NSCFConstantString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0x

...有没有一种方法可以使用左侧的属性名称构建这样的查询 - 一个 'contained_by' 查询,就像它一样?

...is there a way of constructing such a query with the attribute name on the left hand side - a 'contained_by' query, as it were?

附注.搜索 SO,我只找到了通过将文本拆分为组成词的解决方案,在我的情况下,这将小于理想的!这是唯一可行的方法吗?

PS. Searching SO, I've only found solutions by splitting the text into component words which, in my scenario, would be less than ideal! Is this the only type of approach that's viable?

推荐答案

使用数组构建正则表达式字符串,并在谓词中使用 MATCHES.

Build a regex string with your array and use MATCHES in your predicate.

[NSPredicate predicateWithFormat:@"%@ MATCHES '*(Audi|Mercedes)*'", testString];

根据汽车品牌过滤汽车:

To filter cars based on their brand:

NSArray *brands = [@"Audi", @"Mercedes"];
[NSPrediate predicateWithFormat:@"carBrand IN %@", brands];

这篇关于为 'CONTAINED_BY' 编写 NSPredicate;文本查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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