ios - 带有数组 Swift 的核心数据过滤器谓词

标签 ios arrays swift core-data nspredicate

我试图通过传入一个字符串数组来从我的核心数据存储中提取对象,并仅提取类别与数组中的内容匹配的对象。

我已经能够让这段代码工作,除了它只使用数组中的第一项,并且不会遍历数组并匹配其余项。

这是适用于此的代码。我正在使用接受数组的 NSPredicate 重载。

    func filterTopicCategories() {
        fetchController.topicFetchRequest.predicate = NSPredicate(format: "topicCategory == %@", argumentArray: selectedCategories)
        topicsToSelectFrom = fetchController.fetchTopics()
        }

我已经仔细阅读了有关谓词的 Apple 文档以及所有其他内容,但似乎无法完全弄清楚。我也花了几个小时在谷歌上搜索。我不确定我是否只是没有正确理解某些事情,或者如果我只是做错了,我不确定。任何帮助将不胜感激。

谢谢

最佳答案

参数 argumentArray 是一个值数组,用于替换格式字符串中的占位符,如 %@

您正在寻找 IN 运算符:

IN

Equivalent to an SQL IN operation, the left-hand side must appear in the collection specified by the right-hand side. For example, name IN { 'Ben', 'Melissa', 'Nick' }. The collection may be an array, a set, or a dictionary — in the case of a dictionary, its values are used. In Objective-C, you could create a IN predicate as shown in the following example:

NSPredicate *inPredicate = [NSPredicate predicateWithFormat: @"attribute IN %@", aCollection]; 

where aCollection may be an instance of NSArray, NSSet, NSDictionary, or of any of the corresponding mutable classes.

所以如果topicCategory是一个字符串写

fetchController.topicFetchRequest.predicate = NSPredicate(format: "topicCategory IN %@", selectedCategories)

关于ios - 带有数组 Swift 的核心数据过滤器谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43435586/

相关文章:

iOS swift URLScheme 无需打开其他应用程序即可静默发布

ios - 重用 UITableViewCell 时如何初始化 UI 事物

ios - View 对象/状态行为的属性

iOS 数据保护和安全文件

java - Scanner next() - 如何替换换行符 [java]

ios - 直接从 xib 文件实例化 UIViewController 哪个更好?

objective-c - 从 UITableView 获取 UITextField 文本

ios - 为不同语言的项目添加两个 Storyboard

javascript - 如何从以下 xml 制作层次结构数组?

c - C语言中如何从逗号分隔的字符串中获取子字符串