使用数组Swift的核心数据过滤器谓词

bsh*_*k84 7 arrays core-data nspredicate ios swift

我试图通过传入一个字符串数组来拉出我的核心数据存储中的对象,并且仅拉动具有与数组中的类别匹配的类别的对象.

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

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

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

我已经把关于谓词的Apple文档倾注了所有这些,而且似乎无法弄明白.我花了几个小时在谷歌周围搜索.我不确定我是不是只是没有正确理解,或者如果我只是完全错了,我不确定.任何帮助将不胜感激.

谢谢

vad*_*ian 8

该参数argumentArray用于替换%@格式字符串中的占位符的值数组.

您正在寻找IN运营商:

等效于SQL IN操作,左侧必须出现在右侧指定的集合中.例如,name IN { 'Ben', 'Melissa', 'Nick' }.集合可以是数组,集合或字典 - 在字典的情况下,使用其值.在Objective-C中,您可以创建IN谓词,如以下示例所示:

NSPredicate *inPredicate = [NSPredicate predicateWithFormat: @"attribute IN %@", aCollection]; 
Run Code Online (Sandbox Code Playgroud)

其中aCollection可以是一个实例的NSArray,NSSet, NSDictionary或的,任何相应的可变类.

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

fetchController.topicFetchRequest.predicate = NSPredicate(format: "topicCategory IN %@", selectedCategories)
Run Code Online (Sandbox Code Playgroud)