core-datanspredicatefetchrequest

Core data predicates - what’s the benefit?


I recently started learning Core Data and I totally see why having managed observable objects brings huge benefits.

The part that’s not clear to me is why predicates are deemed so powerful when they, in my perception, are just sqlishy snippets. That wouldn‘t be a problem at all as it also makes for readable code. But the snippets contain object properties in the form of strings, as in

„myProperty == @d“

If I refactor my entities so the property gets renamed, I now have to go through each FetchRequest and fix the predicate string. If not, the error is not discovered at build time, but at runtime.

This is at least my understanding (which likely is a misunderstanding) and it annoys me so much, that I wanted to ask for insights or advice on this topic.


Solution

  • The "snippets", as you call them, can contain property names, but you don't have to use the property names as literal strings. You can instead use the %K placeholder to substitute in the relevant property name, and use the #keyPath feature to create the string from the (compiler-verified) property name:

    NSPredicate(format:"%K == %@",#keyPath(MyEntityClass.myProperty),...)
    

    See here for further information on the %K placeholder, and here for a discussion on using #keyPath.

    So no need to be annoyed - you can ensure that your predicates are verified at compile time and sleep more easily.