处理addPersistentStoreWithType中的错误

时间:2012-12-10 18:22:11

标签: objective-c core-data fatal-error

我试图在iPhone上创建持久存储协调器时查找有关处理错误的信息。我已经实现了轻量级迁移

   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;

这是基于Apple的代码,增加了对轻量级迁移的支持。

如果应用程序在此处仍然遇到错误,我找不到任何有关处理错误的信息。在我看来,如果无法创建数据库,则根本无法使用该应用程序。

  • 我是否只是要求用户尝试重新安装应用程序并显示相关信息?
  • 我可以在添加有关错误的提示时保留abort()语句,还是会导致应用程序被Apple拒绝?

1 个答案:

答案 0 :(得分:15)

在这种情况下调用abort()是不可能的。任何崩溃的应用都将被Apple拒绝。并没有解决问题:再次启动应用程序将找到相同的存储文件,因此再次失败。

出于同样的原因,重新安装应用程序没有帮助,这将是一个糟糕的用户体验。

当然,如果迁移已经过测试,则不应出现这种情况。但是,如果发生此致命错误且您的应用无法打开数据库,则必须创建一个新数据库。

确切的步骤取决于数据库中存储的内容以及是否/如何恢复数据。所以你可以

  • 使用[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]删除旧数据库文件,或将程序资源中的默认数据库文件复制到storeURL
  • 再次致电_persistentStoreCoordinator addPersistentStoreWithType:...以打开新数据库。
  • 可能会再次使用来自服务器的数据填充数据库,或者无需重新填充数据。