如何使用基于数组的 NSPredicate 过滤核心数据对象

How to filter Core Data objects with NSPredicate based on array

假设我在 Core Data 中有一些基于以下对象的数据:

class TestObject {
   var name: String
   var type: String
}

type 可以具有以下名称之一:"red"、"green"、"blue"、"black".

现在我想过滤我的数据不是基于一种类型,而是一组类型,像这样:

public static func typePredicate(types: [String]) -> NSPredicate {

    return NSPredicate(format: "type == %@", types) // this line should test for an array of types, not one type
}

这可能与 NSPredicate 有关吗?

你可以试试下面的方法

[NSPredicate predicateWithFormat:@"ANY %K IN %@",object.field,types]

编辑: 在Swift

var types = ["Red","Blue","Green"]
var predicate : NSPredicate = NSPredicate(format: "ANY %K IN %@", 
                               argumentArray: [object.field, types])