Adrian
Adrian

Reputation: 20058

How to filter Core Data objects with NSPredicate based on array

Let's say I have some data inside Core Data based on the following object:

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

type can have one of the following names: "red", "green", "blue", "black".

Now I want to filter my data not based on one type, but an array of types, something like this:

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

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

Is this possible to do with NSPredicate ?

Upvotes: 1

Views: 2411

Answers (1)

Suresh Kumar Durairaj
Suresh Kumar Durairaj

Reputation: 2126

You could try something like below

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

EDIT: In Swift

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

Upvotes: 3

Related Questions