2012-03-01 55 views
1

我的提取請求工作正常,我得到我提取的對象沒有任何問題。我想要做的是在實體不存在的情況下處理錯誤。問題是,我無法處理錯誤,因爲當我調用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 
} 

正如我所說的,還有隻要實體存在是沒有問題的,但我想,如果它不存在處理錯誤。任何想法?乾杯

+1

嗯..你不應該做一個讀取請求對於不存在的實體類型。在什麼情況下你會需要這樣做? – 2012-03-01 19:32:58

+0

其實很好的問題:/ ...我認爲我需要檢查它在不同版本的應用程序之間同步的情況下,但我實際上以不同的方式捕捉到這種情況。謝謝哈哈......但要100%肯定,爲什麼不檢查實體是否存在,以免應用程序崩潰? – wolfrevo 2012-03-01 19:56:12

+0

再次這應該永遠不會發生,你應該只參考你知道存在的實體。如果您更新應用程序以刪除此實體,則應該更改您的代碼以不再使用它。您應該將您的Core Data模型設置爲進行版本控制,以便您可以輕鬆遷移數據庫。 – 2012-03-02 12:32:13

回答

1

你可以問模型如果這樣的實體存在:

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