我的应用程序中有以下数据模型:
基本上我想存储国家名称和城市名称。每个城市属于一个国家,一个国家包含 0 - n 个城市。
在我现在向某个国家/地区添加新城市之前,我需要知道该国家/地区是否已经包含具有此名称的城市。
直到现在我这样做:
- (BOOL)countryForName:(NSString *)countryName containsCity:(NSString *)cityName {
Countries *country = [self countryForName:countryName];
NSSet *cityNames = [country valueForKey:@"cities"];
for (Cities *city in cityNames) {
if ([city.cityName isEqualToString:cityName]) {
return YES;
}
}
return NO;
}
这显然很慢,我需要的是具有正确谓词的等效提取。我搜索一个这样的实体:
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Countries" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"countryName" ascending:YES];
NSArray *sortDescriptors = @[sortDescriptor];
fetchRequest.sortDescriptors = sortDescriptors;
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"GetCountryList"];
aFetchedResultsController.delegate = self;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"countryName == %@", countryName];
[aFetchedResultsController.fetchRequest setPredicate:predicate];
但是,如果搜索涉及多个实体,我该怎么做?或者换句话说:如何只为一个国家添加唯一的城市名称?