2012-12-10 45 views
6

我想在iPhone上創建持久存儲協調器時查找有關處理錯誤的信息。我已經實現輕量級遷移addPersistentStoreWithType中的處理錯誤

NSError *error = nil; 
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: 
         [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, 
         [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; 
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; 
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) { 
    /* 
    Replace this implementation with code to handle the error appropriately. 

    abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 

    Typical reasons for an error here include: 
    * The persistent store is not accessible; 
    * The schema for the persistent store is incompatible with current managed object model. 
    Check the error message to determine what the actual problem was. 


    If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory. 

    If you encounter schema incompatibility errors during development, you can reduce their frequency by: 
    * Simply deleting the existing store: 
    [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil] 

    * Performing automatic lightweight migration by passing the following dictionary as the options parameter: 
    @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES} 

    Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details. 

    */ 
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
    abort(); 
}  

return _persistentStoreCoordinator; 

這是基於蘋果的代碼與輕量級遷移增加的支持。

如果應用程序在這裏仍然遇到錯誤,我找不到處理錯誤的任何信息。在我看來,如果數據庫無法創建,那麼應用程序根本無法使用。

  • 我只是要求用戶嘗試重新安裝應用程序並顯示相關信息?
  • 我可以在添加關於錯誤的提示時保留abort()語句,否則會導致應用程序被Apple拒絕?

回答

14

在這種情況下調用abort()是不成問題的。任何崩潰的應用程序將被Apple拒絕。它不能解決問題:再次啓動應用程序將找到相同的存儲文件,因此再次失敗。

出於同樣的原因,重新安裝該應用程序並沒有幫助,這將是一個不好的用戶體驗。

當然,如果遷移已經過測試,情況就不會發生。但是,如果發生此致命錯誤,並且您的應用程序無法打開數據庫,則必須創建新的數據庫。

確切的步驟取決於存儲在數據庫中的內容以及是否/如何恢復數據。所以,你可以

  • [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]刪除舊的數據庫文件,或者從你的程序資源複製一個默認的數據庫文件storeURL
  • 呼叫_persistentStoreCoordinator addPersistentStoreWithType:...再次打開新的數據庫。
  • 可能會再次使用來自服務器的數據填充數據庫,或重新創建數據所需的任何操作。
+0

謝謝您的幫助,我已經加入試圖刪除數據庫,然後重新創建它的數據庫無法從服務器加載。 如果在這一點上仍然失敗,我該怎麼辦? –

+1

這將是一個不應該正常發生的致命錯誤,所以我認爲在這種情況下可以放棄(),以便獲得崩潰日誌以通知您有關該問題。 –