CoreData predicate using subquery

50 Views Asked by At

I have two CoreData entities with their properties:

Asset

  • caches: [Cache] (to-many)

Cache

  • key: String
  • value: String
  • asset -> Asset (to-one, inverse of caches)

I want to make a NSPredicate which evaluates wether an Asset has a cache matching a given key and a value containing a given string (in other terms, I want to check the value of the cache with a given key associated to the Asset).

And I need it to be the less time consuming possible because there are thousands of entries which will be tested each time.

ChatGPT offered two solutions, but I'm pretty sure the first one won't work.

Solution 1

NSPredicate(format: "ANY caches.key == %@ && ANY caches.contentText CONTAINS[c] %@", keyToSearch, contentTextToSearch)

I think this predicates will return instances that match either the key, or either the value test, but not necessarily both.

Solution 2

NSPredicate(format: "SUBQUERY(caches, $cache, $cache.key == %@ AND $cache.contentText CONTAINS[c] %@).@count > 0", keyToSearch, contentTextToSearch)

That should work but I'm wondering if there would not be a more efficient way to do that?

0

There are 0 best solutions below