ios - 无法处理 executeFetchRequest 错误

标签 ios core-data nsmanagedobjectcontext nsfetchrequest

我的提取请求工作正常,我可以毫无问题地获取我提取的对象。我想做的是在实体不存在的情况下处理错误。问题是,我无法处理错误,因为当我调用 executeFetechRequest: error: 时应用程序崩溃,没有任何警告。

我的提取看起来像:

NSManagedObjectContext *context = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = [NSEntityDescription entityForName:@"Info" inManagedObjectContext:context];
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"infoID" ascending:YES]];
[request setReturnsObjectsAsFaults:NO];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"infoID like %@",[a substringFromIndex:13]];
request.predicate = predicate;
request.fetchBatchSize = 1;

NSError *error = nil;

NSArray *results = [context executeFetchRequest:request error:&error];

if (error == nil) {
    ...
}
else {
    //handle error
}

正如我所说,只要实体存在就没有问题,但如果它不存在,我想处理错误。任何想法?干杯

最佳答案

您可以询问模型是否存在这样的实体:

    NSArray *entities = managedObjectModel.entities;
    BOOL canExecute=NO;
    for(NSEntityDescription *ed in entities) {
       // check if entity name is equal to the one you are looking for
       if(found) {
          canExecute=YES;
          break;
       }
    }

   if(canExecute) {
     // execute your request and all the rest...
   } else {
     NSLog(@"Entity description not found");
   }

如果不存在则不执行获取请求

关于ios - 无法处理 executeFetchRequest 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9522599/

相关文章:

android - 使用带有 react-native 的 WebView 设置用户代理

objective-c - 如何更改 iOS 中 TableView 和 Button 控件的颜色?

cocoa - Lion 沙箱化现有的 Snow Leopard 核心数据应用程序

ios - 获取 NSManagedObjectContext

iphone - 如何创建 NSManagedObjectContext

ios - 在 ios 中缓存视频

ios - 每次应用程序启动时,都会从 "_GLOBAL__I_a"触发 "ImageLoaderMachO::doModInitFunctions"异常中断

ios - 检索用户的关注者的谓词

objective-c - iOS 11 - 核心数据 - UIColor 不再用作可转换属性

cocoa - 如何在基于文档的 Core Data/Cocoa 应用程序中获取当前 NSManagedObjectContext?