gpt4 book ai didi

core-data - CoreData 检查对多关系是否包含对象

转载 作者:行者123 更新时间:2023-12-04 10:19:00 25 4
gpt4 key购买 nike

我的应用程序中有以下数据模型:

data model

基本上我想存储国家名称以及城市名称。每个城市属于一个国家,一个国家包含 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通常用于显示内容
在表 View 中获取请求,所以这里不需要。

关于core-data - CoreData 检查对多关系是否包含对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16788917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com