假设您有一个CoreData
名为Countries
. 这个国家有属性countryName
。要检查是否存在 type 的实体Countries
,我调用以下方法:
- (BOOL)countryExistsWithName:(NSString *)countryName{
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Countries"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"countryName == %@, countryName];
[fetchRequest setPredicate:predicate];
NSError *error;
NSUInteger count = [self.managedObjectContext countForFetchRequest:fetchRequest error:&error];
if (count == NSNotFound) {
// error
NSLog(@"error");
return NO;
}
if (count > 0) {
// at least one country found
return YES;
}
return NO;
}
编辑:如果您不想要求某个countryName
,您只需检查 all Countries
,执行以下获取:
- (NSInteger )countAllCountries{
// We use an NSPredicate combined with the fetchedResultsController to perform the search
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Countries"];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"countryName" ascending:YES];
fetchRequest.sortDescriptors = @[sortDescriptor];
NSError *error;
NSUInteger count = [self.managedObjectContext countForFetchRequest:fetchRequest error:&error];
if (count == NSNotFound) {
// error
NSLog(@"error");
return 0;
}
if (count > 0) {
// at least one country found
return count;
}
return count;
}
使用这种方法,您应该很容易确定您的数据源是否为空。希望能帮助到你