NSPredicate IN query from array elements

ardevd picture ardevd · Feb 3, 2016 · Viewed 11.2k times · Source

Apologies for a quirky title. I have an array of Ints and I would like to define an NSPredicate that will filter out items with connectionType equals to a value contained in the array.

So basically something like:

fetchRequest.predicate = NSPredicate(format: "connectionType IN { all items in array }

I've found some Objective C examples that I think deals with this, but I just got into iOS development and have only worked with Swift, so some help here would be greatly appreciated :)

I tried doing this:

 fetchRequest.predicate = NSPredicate(format: "connectionType IN \(myIntArray)"

However, this returns an NSInvalidArgumentException. I feel I'm close though.

NSInvalidArgumentException', reason: 'Unable to parse the format string "connectionType IN [28, 28]" 

If I do the following:

fetchRequest.predicate = NSPredicate(format: "connectionType IN %@", myArray)

I get this error instead:

NSInvalidArgumentException', reason: 'unimplemented SQL generation for predicate : (connectionType IN {28, 28})'

Answer

Anatoli P picture Anatoli P · Feb 4, 2016

You would construct a predicate like this:

NSPredicate(format:"connectionType IN %@", yourIntArray)

I hope this is helpful.