【问题标题】:How to solve coreData error in AppDelegate?如何解决 AppDelegate 中的 coreData 错误?
【发布时间】:2017-02-25 15:54:09
【问题描述】:

其实我在 iOS 10 的 coreData 方面有一些经验。
但我现在创建了一个目标是#version 8.0 及更高版本的应用程序。
首先,我创建了一个包含 coreData 的应用程序。所以他们会在 AppDelegate 中自动为我生成一个代码作为 iOS 10 标准。当我将目标 10 更改为 8.0 时,AppDelegate 会显示一些错误。

AppDelegate 中的错误

如何解决这个问题?我想在 ios 8.0 及更高版本中使用 coreData。

 // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded 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.
        */
        let container = NSPersistentContainer(name: "coreDataTestForPreOS")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() 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 parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() 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.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

}

let ad = UIApplication.shared.delegate as! AppDelegate
let context = ad.persistentContainer.viewContext

【问题讨论】:

  • 在下面查看我的答案。

标签: ios core-data swift3


【解决方案1】:
var context: NSManagedObjectContext?

if #available(iOS 10.0, *) {
    context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
} else {
    // iOS 9.0 and below - however you were previously handling it
    guard let modelURL = Bundle.main.url(forResource: "Model", withExtension:"momd") else {
        fatalError("Error loading model from bundle")
    }
    guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
        fatalError("Error initializing mom from: \(modelURL)")
    }
    let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
    context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let docURL = urls[urls.endIndex-1]
    let storeURL = docURL.appendingPathComponent("Model.sqlite")
    do {
        try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
    } catch {
        fatalError("Error migrating store: \(error)")
    }

}`

【讨论】:

  • 我在哪里写的?你能编辑我上面发布的代码并重新发布吗
  • 在 saveContext() 中?
【解决方案2】:

NSPersistentContainer 方便之前有NSPersistentStoreCoordinator。您需要创建其中之一:

    if 
      let modelURL = Bundle.main.url(forResource: "Model", withExtension: "momd"),
      let model = NSManagedObjectModel(contentsOf: modelURL),
      let psc = NSPersistentStoreCoordinator(managedObjectModel: model) {
          ...
    }

然后通过.addPersistentStore(ofType:configurationName:at:options)创建并添加一个或多个NSPersistentStores。

【讨论】:

  • 在哪里?我不明白。我是 iOS 的初学者而不是专家,请简要说明我在哪里添加以及它是如何工作的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-04
  • 1970-01-01
  • 1970-01-01
  • 2011-06-07
  • 1970-01-01
  • 2017-10-06
  • 2020-11-01
相关资源
最近更新 更多