无法处理executeFetchRequest错误
问题描述:
我的提取请求工作正常,我得到我提取的对象没有任何问题。我想要做的是在实体不存在的情况下处理错误。问题是,我无法处理错误,因为当我调用executeFetechRequest时,应用程序崩溃:error:没有任何警告。无法处理executeFetchRequest错误
我取的样子:
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");
}
,如果不存在,你不执行抓取reuest
嗯..你不应该做一个读取请求对于不存在的实体类型。在什么情况下你会需要这样做? – 2012-03-01 19:32:58
其实很好的问题:/ ...我认为我需要检查它在不同版本的应用程序之间同步的情况下,但我实际上以不同的方式捕捉到这种情况。谢谢哈哈......但要100%肯定,为什么不检查实体是否存在,以免应用程序崩溃? – wolfrevo 2012-03-01 19:56:12
再次这应该永远不会发生,你应该只参考你知道存在的实体。如果您更新应用程序以删除此实体,则应该更改您的代码以不再使用它。您应该将您的Core Data模型设置为进行版本控制,以便您可以轻松迁移数据库。 – 2012-03-02 12:32:13