我正在尝试构建核心数据存储的查询,该查询在实体的属性值出现在较长的字符串中时检索该实体的属性值;
即,不是寻找属性值包含一个(较短的)字符串的实例:
request.predicate = [NSPredicate predicateWithFormat:@"carBrand contains[c] 'merced'"]
我想找到(实体的)实例,其属性值“包含在”任意(更长)字符串中:
NSString* textString = @"Elaine used to drive Audis, but now owns a Mercedes";
request.predicate = [NSPredicate predicateWithFormat:@"%@ contains[c] carBrand", textString ];
(即检索包含 carBrand = @"Audi"和 carBrand = @"Mercedes"的对象的数组)
在我的尝试中,NSPredicate 似乎不喜欢右侧带有属性名称的表达式并抛出错误...
[__NSCFConstantString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0x
...有没有一种方法可以用左侧的属性名称构造这样的查询 - 可以说是一个'contained_by' 查询?
附言。搜索 SO,我只找到了 solutions by splitting the text into component words在我的情况下,这不太理想!这是唯一可行的方法吗?
最佳答案
用您的数组构建一个正则表达式字符串,并在您的谓词中使用 MATCHES
。
[NSPredicate predicateWithFormat:@"%@ MATCHES '*(Audi|Mercedes)*'", testString];
根据品牌过滤汽车:
NSArray *brands = [@"Audi", @"Mercedes"];
[NSPrediate predicateWithFormat:@"carBrand IN %@", brands];
关于ios - 为 'CONTAINED_BY' 文本查询编写一个 NSPredicate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26778320/