我的应用程序中具有以下数据模型:
基本上,我想存储国家名称和城市名称。每个城市属于一个国家,一个国家包含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];
但是,如果搜索涉及多个实体,该怎么办?换句话说:如何仅为一个国家/地区添加唯一的城市名称?非常感谢!
[如果您要检查给定的国家/地区对象是否已包含具有名称的城市,你可以做
Countries *country = ...
NSString *cityName = ...
if ([[country valueForKeyPath:@"cities.name"] containsObject:cityName]) {
// ...
}
或者,使用获取请求:
NSString *countryName = ...
NSString *cityName = ...
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Countries"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"countryName == %@ AND ANY cities.cityName == %@", countryName, cityName];
[fetchRequest setPredicate:predicate];
NSError *error;
NSUInteger count = [self.managedObjectContext countForFetchRequest:fetchRequest error:&error];
if (count == NSNotFound) {
// error
} else if (count == 0) {
// no matching country
} else {
// at least one matching country
}
注意,NSFetchedResultsController
通常用于显示在表视图中获取请求,因此此处不需要。