Search code examples
swiftrealm

Unable to filter after Date in Realm swift


I'm trying to apply a filter on realm which includes a Date but with no luck.

I've found out that Date object cannot be passed because the %@ format expects a Foundation object as argument, so I've applied a cast to NSDate.

let newDate = Date()
realm.objects(E.self)
            .filter(String(format: "%@ <= %@", key, newDate as NSDate)).first

The issue that appears is "Unable to parse the format string timestamp==2020-03-20 08:21:00 +0000"

key is the name of the field, which in this case it is "timestamp" and on the model it has the type Date.

Any input is appreciated.

Thanks


Solution

  • You should use:

    .filter("\(key) <= %@", newDate as NSDate)
    

    This is calling the overload of Realm's filter method that accepts a format and arguments.

    String(format:) is not the right thing to use here, as that just does general string formatting. But here, you want the date to be formatted according to the rules of NSPredicate formats. On the other hand, the key can just be interpolated into the string because the name of the table column doesn't need a special format.

    If key comes from a UITextField or something like that, then you might need to beware of injection attacks as well, and validate and/or escape the key properly beforehand.