2

我花了很多时间让我的 Core Data 模型有效地为我的 iOS 应用程序开发工作。在大多数情况下,我的一切工作都很顺利,但前几天我在加载数据时遇到了一个独特的错误,这只是偶然。我刚开始在我的 iPhone 上运行我的应用程序进行测试,就在它启动并开始使用 Core Data 加载数据时,我姐姐打电话给我。时机相当偶然,因为该中断似乎abort()已从persistentStoreCoordinator.AppDelegate

这是我所指的代码:

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
    // Create the coordinator and store
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("DataModel.sqlite")
    var failureReason = "There was an error creating or loading the application's saved data."
    let mOptions = [NSMigratePersistentStoresAutomaticallyOption: true,
        NSInferMappingModelAutomaticallyOption: true]
    do {
        try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: mOptions)
    } catch {
        // Report any error we got.
        var dict = [String: AnyObject]()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
        dict[NSLocalizedFailureReasonErrorKey] = failureReason

        dict[NSUnderlyingErrorKey] = error as NSError
        let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
        // Replace this 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.
        NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")

        abort()  // THIS
    }

    return coordinator
}()

显然,我看到苹果在哪里评论说该abort()功能只需要在开发期间使用,并且应该在生产中删除一次,但我想知道是否有人可以告诉我如何正确处理这种类型的错误?

我没有加载大量数据,我想在这种情况下我需要做的就是重新开始加载过程。

我想我真正要问的是,一旦发现错误,是否有简单的方法告诉它重试,还是我必须手动返回在应用程序启动时调用数据获取的方式?

4

1 回答 1

0

您可以重试,但通常没有意义。如果添加持久存储失败,通常没有机会再加载它,因为数据已损坏或不可读。剩下的唯一选择是删除现有文件,创建一个新文件,然后(如果可用)从您可能使用的任何云服务中恢复数据。

但是,如果您认为值得,您可以再试一次。再次调用addPersistentStoreWithType,使用相同的参数,看看它是否有效。检查返回值——如果它不是 nil 并且没有抛出错误,那么你就可以开始了。在您从这个惰性 var 初始化返回之前,您可以根据需要多次调用该方法。

于 2016-08-19T22:55:37.973 回答