0
votes

First of all, I have to apologize for that silly question. Unfortunately I couldn't figure out how to implement after reading so many posts. Sorry for that. So, here is my question: I have two entities, regions and counries. Each region belongs to a country and every country has several regions. In my application I chose a country and want to display all its regions.To keep it simple, country and region both have the attribute name and region has a relationship 'country'. Now I have to select all the regions of a country:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *desc = [[model entitiesByName] objectForKey:@"Region"];
[request setEntity:desc];

NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sd]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"any country LIKE[c] 'aCountry'"];
[request setPredicate:predicate];

That one looks nice, but doesn't work, because country is a relationship and because of this the names of the countries are not stored in the relationship, but in the entity country. I then tried another way:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"any Country.name LIKE[c] 'aCountry'"];

This results in an error:

NSInvalidArgumentException', reason: 'keypath Country.name not found in entity '

Now, what is the best way to get my regions?

1
So is "country" an attribute of your Region NSManagedObjectSubclass? - GeneralMike
No, it is just a relationship. - usermho

1 Answers

1
votes

If aCountry is an object of the Country entity, and country is the to-one relationship from Region to Country, then the following fetch request finds all regions of that country:

Country aCountry = ... ;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Region"];
// ... add sort descriptor (optional)
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"country = %@", aCountry];
[request setPredicate:predicate];

But note that if you also have defined an inverse to-many relationship regions from Country to Region then you get all regions of the country just by

NSSet *regionsForCountry = aCountry.regions;

or, if you prefer an array:

NSArray *regionsForCountry = [aCountry.regions allObjects];