我试图通过传入一个字符串数组来从我的核心数据存储中提取对象,并仅提取类别与数组中的内容匹配的对象。
我已经能够让这段代码工作,除了它只使用数组中的第一项,并且不会遍历数组并匹配其余项。
这是适用于此的代码。我正在使用接受数组的 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 aIN
predicate as shown in the following example:NSPredicate *inPredicate = [NSPredicate predicateWithFormat: @"attribute IN %@", aCollection];
where
aCollection
may be an instance ofNSArray
,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/