0

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.

ximarin
  • 401
  • 3
  • 14
  • Now that's with `%K` + `#keyPath()` you're good, it's unclear if you're also asking this, but the real advantage, is that the filter is inside the query, and so you don't fetch all (for "nothing") and fetch only the needed one. – Larme Jan 25 '21 at 21:05
  • Thanks, yes, this is an obvious benefit and I already have sandbox implementations that use a bunch of predicates (all in a single string at the moment). I assumed at the very beginning that predicates are for Core Data what the CriteriaAPI is for JPA where there is literally no String anywhere and I can conditionally add or remove criterias (as it's all expressed in code). I've already stumbled upon NSCompoundPredicate which might be the way to get conditional criterias for core data. – ximarin Jan 27 '21 at 08:54

1 Answers1

1

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.

pbasdf
  • 21,386
  • 4
  • 43
  • 75
  • Thanks, appreaciated! I stumbled upon the %K placeholder, but the sample code also used a string as replacement. #keypath was what I was looking for! Also thanks for the links, I already got heavily confused by the first article earlier :D – ximarin Jan 24 '21 at 11:25