JAHelia
JAHelia

Reputation: 7932

Trying to write a predicate to compare against the first object of a to-many relationship

I use this predicate [NSPredicate predicateWithFormat:@"ANY lists.name LIKE[cd] %@", listName] to compare the search string (listName) with an ordered to-many relationship named lists, however, there is a design requirement that I have to compare the search string (listName) against only the first element of the ordered set in the to-many relationship, so I need something like the following pseudocode to be done using a CoreData predicate:
[NSPredicate predicateWithFormat:@"lists.firstObject.name LIKE[cd] %@", listName];

thank you in advance

p.s I know it's possible to fetch the first object of that ordered to-many relationship and then compare the listName against that object, but i won't use this approach 'coz it will be an overhead for the app since this predicate is a part of a big loop.

Upvotes: 0

Views: 156

Answers (2)

Mundi
Mundi

Reputation: 80273

I have answered this question before. Ordered relationships have many issues - they are more of a convenience than a hard data modelling feature.

You should simply model the order of the objects as well, e.g. with an attribute order of type number. Your predicate is then

[NSPredicate predicateWithFormat:
      @"ANY lists.name LIKE[cd] %@ && order = 1", listName];

Upvotes: 2

Dave DeLong
Dave DeLong

Reputation: 243156

Typing on my phone so excuse the brevity.

I'm pretty sure you can do:

"lists[0].name like[cd] %@", ...

Also:

"lists[first].name like [cd] %@", ...

HOWEVER, I don't know if Core Data can evaluate that predicate. You'll have to try it and find out.

Upvotes: 2

Related Questions