문제

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" ?

도움이 되었습니까?

해결책

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.

다른 팁

You do not need to use the ANY key word if you have set up you core data model correctly. Specifically Credit cards need to have a person relationship back to the person object (you should get a warning if you didn't do this). Then you could combine both predicates into one like this

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"person == %@ AND valid_date == %@", currentUser, valid_date];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top