Search code examples
ioscore-dataentity-relationshipnspredicatensfetchrequest

NSPredicate and Core Data: retrieve objects among relationships


I have a Core Data model structure like the following:

Product <-->> OrderProduct where the relationship (from Product to OrderProduct) is called productOrders while the inverse is called product

Order <-->> OrderProduct where the relationship is called orderProducts while the inverse is called order

Client <-->> Order where the relationship is called orders while the inverse is called client

Within an UIViewController I'm using a NSFetchRequest associated with the following predicate:

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"(ANY productOrders.order.client.code == %@)", clientCode];

The predicate works well. I'm able to retrieve products for one (or more) orders that are associated with a specific client.

Now I have to add another step. Find the last order (ordering by date) for a specific client. I've tried the following predicate but it doesn't work:

  NSPredicate* predicate = [NSPredicate predicateWithFormat:@"(ANY productOrders.order.client.code == %@ AND [email protected])", clientCode];

where orderDate is of type NSDate.

Do I have to use a SUBQUERY? How can I achieve this? Thank you in advance.


Solution

  • I was able to fix the issue passing the date externally. In other words, I first calculated the last order date for a specific client and then I passed it to the interested element (the one that implement the request).

    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"ANY productOrders.order.client.code == %@ AND productOrders.order.orderDate == %@", clientCode, lastDate];
    

    I don't know if could be correct but it works.

    Hope it helps.