Search code examples
iosnspredicaterelationships

CoreData - Fetch request with relationship object


please confirm if i understand that right...

Imagine there is an entity 'person' and an entity 'credit_card'. So one 'person' can have many 'credit_card's.

The person entity has the attributes: name: STRING and age: INT and relationship: creditcards (to many) inverse

and the credit card entity has: card_number: INT and valid_date: DATE and relationship: card_user (to one) inverse

In my code i have a specific person (ManagedObject) called f.e. Person *currentUser. If i now want to get all credit cards of this specific person with a specific 'valid_date' i would create a fetch request (for Entity 'credit_card') with following predicates:

NSPredicate *predicate1 = [NSPredicate predicateWithFormat:
@"valid_date == <NSDate object>"];

NSPredicate *predicate2 = [NSPredicate predicateWithFormat:
@"ANY card_user like currentUser"];

This predicate works well for me, but is that the right way? Should i really ask for: "ANY relationship name like ManagedObject" ?


Solution

  • If I'm understanding what you want correctly, all you need to do is use the creditcards property on your Person *currentUser and filter it down:

    NSSet *setOfCreditCards = currentUser.creditcards;
    NSPredicate *filter = [NSPredicate predicateWithFormat: @"valid_date == %@", date];
    NSSet *cardsWithValidDates = [setOfCreditCards filteredSetUsingPredicate:filter];
    

    The reason you tell CoreData about relationships is to avoid making another query from scratch.