swift NSPredicate logical OR

2020-04-26 02:16发布

问题:

I've got a single string substitution working with NSPredicate but returning core data records that contain either StringA or StringB doesn't seem to be something I can figure out. I want something like this:

let filter = NSPredicate(format: ("%K = %@", "type", "StringA") OR ("%K = %@", "type", "StringB"))

But of course that doesn't work. Help?

回答1:

You have to specify a format string, followed by a comma-separated list of arguments to substitute into the format:

let filter = NSPredicate(format:"%K = %@ OR %K = %@", "type", "StringA", "type", "StringB")

If the keys are not reserved words and do not contain special characters then you can specify them directly in the format string:

let filter = NSPredicate(format:"type = %@ OR type = %@", "StringA", "StringB")