Group Group Group Group Group Group Group Group Group

Realm Filtering - Using NSPredicate vs. String

#1

Hi,

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!

#2

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

#3

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:

Shai.