0

首先,我必须为这个愚蠢的问题道歉。不幸的是,在阅读了这么多帖子后,我无法弄清楚如何实施。对此感到抱歉。所以,这是我的问题:我有两个实体,地区和国家。每个地区属于一个国家,每个国家都有几个地区。在我的应用程序中,我选择了一个国家并希望显示其所有地区。为简单起见,国家和地区都具有属性名称,地区具有关系“国家”。现在我必须选择一个国家的所有地区:

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];

那个看起来不错,但不起作用,因为国家是一种关系,因此国家的名称不存储在关系中,而是存储在实体国家中。然后我尝试了另一种方法:

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

这会导致错误:

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

现在,获得我的地区的最佳方式是什么?

4

1 回答 1

1

如果aCountryCountry实体的对象,并且country是RegionCountry的一对一关系,则以下获取请求会查找该国家/地区的所有区域:

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

但请注意,如果您还定义了从CountryRegion的逆多关系区域,那么您只需通过

NSSet *regionsForCountry = aCountry.regions;

或者,如果您更喜欢数组:

NSArray *regionsForCountry = [aCountry.regions allObjects];
于 2012-12-14T17:31:13.490 回答