无法在AppDelegate coredata,Swift 2

时间:2015-09-29 06:59:14

标签: core-data swift2 appdelegate nserror

我也刚刚更新到Xcode 7,我在AppDelegate.swift中遇到了这个问题

 lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
    // The persistent store coordinator for the application. This implementation creates and return 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
    var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Inclinometer.sqlite")
    var error: NSError? = nil
    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 var error1 as NSError {
        error = error1

        // Report any error we got.
        let dict = NSMutableDictionary()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
        dict[NSLocalizedFailureReasonErrorKey] = failureReason
        dict[NSUnderlyingErrorKey] = error
        error = 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 \(error), \(error!.userInfo)")
        abort()
    } catch {
        fatalError()
    }

    return coordinator
}()

它显示在这一行

error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)

无法使用类型(域,代码,userInfo)的参数列表调用类型为“NSError”的初始化器。如何更改它以使其在Xcode 7中运行?

2 个答案:

答案 0 :(得分:0)

NSError初始值设定项需要[String: AnyObject]类型为userInfo的参数。你必须这样写:

let dict : [String: AnyObject] = [
  NSLocalizedDescriptionKey: "Failed to initialize the application's saved data",
  NSLocalizedFailureReasonErrorKey : failureReason
  NSUnderlyingErrorKey : error
]

另外,我认为你不需要创建一个额外的错误变量(定义在哪里?)并覆盖它。

答案 1 :(得分:-1)

看起来你必须特别注意你在字典中的内容,在XCode 7.0中这适用于我

let dict : [String: AnyObject] = [
        NSLocalizedDescriptionKey: "Failed to initialize the application’s saved data",
        NSLocalizedFailureReasonErrorKey: String(failureReason),
        NSUnderlyingErrorKey: String(error),
    ]
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)