ios - 为 'CONTAINED_BY' 文本查询编写一个 NSPredicate

标签 ios objective-c macos core-data nspredicate

我正在尝试构建核心数据存储的查询,该查询在实体的属性值出现在较长的字符串中时检索该实体的属性值;

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

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/

相关文章:

ios - 如果我使用 Storyboard 中的 "Add missing constraints"选项来在 Storyboard 中分配约束会怎样?

ios - 当为 x86_64 构建包含的文件时,自定义框架会出现错误,该文件不是正在链接的架构

iPhone 命令行单元测试(和文件 I/O)

macos - 用ffmpeg展平两个音轨

python - 在路径中使用带有空格的 virtualenv

ios - 从 scn 导入带有动画的 3D 对象

ios - WatchKit:无法找到接口(interface) Controller 类

ios - CSS 菜单在 iOS 上工作不一致

ios - 快速对齐标签

python - 为什么我在 PyCharm 中的 zsh 没有正确的 $PATH?