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

查看:141
本文介绍了为"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 countByEnumeratingWithState: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?

PS .通过搜索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];

要根据品牌过滤汽车:

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

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

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