Marcone Marcone - 1 month ago 8
Swift Question

Unable to query for date using NSPredicate in Swift

I'm trying to make a fetch for dates later than a specific date. My predicate is as follows:

NSPredicate(format: "date > \(currentDate)")


When I executed the fetch request I caught an exception:

'Unable to parse the format string "date > 2015-07-08 03:00:00 +0000"'


I thought I could make a query like that. What am I doing wrong?

Answer

NSPredicate(format:_:) takes a format string and a list of arguments, but you're passing a simple string. This doesn't work, since this initializer doesn't just call stringWithFormat: on the parameters, but actually looks at the arguments' type information as it's building the predicate.

You can use that initializer by passing the date as an argument:

let datePredicate = NSPredicate(format: "date > %@", currentDate)
Comments