Group Group Group Group Group Group Group Group Group

Realm Filtering - Using NSPredicate vs. String



I’m loving the Realm course! In chapter 5, filtering is being discussed and on page 99 there is the following quote:

" There is also a variation of filter(_) that, instead of a format string, takes an
NSPredicate object, providing safer and more robust filtering. Add to the last example:"

I’m curious to hear why using NSPredicate is safer and more robust? Is it best practice to use NSPredicates over string literals when filtering using realm?

Is it simply that using string literals in a query is more error-prone?

Any help here is greatly appreciated!


@freak4pc Can you please help with this when you get a chance? Thank you - much appreciated! :]


Hey @ckling! Glad to hear you’re enjoying the book :slight_smile:
I think the consideration for using NSPredicate is the same outside and inside Realm.

Using NSPredicate with a format and arguments is less error-prone then manually providing strings, as you’ve mentioned yourself. It lets you provide the Key and Value as arguments (like %K and %V for example).

You can read more about NSPredicate here, since it’s not Realm-specific knowledge, you might enjoy this :

Let me know if I can provide additional help :slight_smile: