2016-03-06 67 views
0

我使用的核心数据,并在我的AppDelegate.swift,我就在这行dict[NSUnderlyingErrorKey] = error as NSError以下错误:向下转换核心数据错误

“错误类型”是无法转换为“NSError”;你的意思是使用'as!'强迫低调?

以下是相应的代码:

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("On The Go.sqlite") 
    var failureReason = "There was an error creating or loading the application's saved data." 
    do { 
     try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) 
    } 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() 
    } 

    return coordinator 
}() 

这里是代码的截图:

enter image description here

我做了错误的建议,但存在着同样的错误。

+0

您使用的是什么版本的Xcode?此代码为我编译... – Whirlwind

+0

我使用Xcode 7.2.1 @Whirlwind –

+0

顺便说一句 - 你可能可以在你的catch块中使用字典文字('dict = [key:value,...]') – nielsbot

回答

2

如果你改变你的catch来包含NSError错误的模式匹配,该怎么办?

do { 
} catch let e as NSError { 
    // handle NSError case 
} catch { 
} 

由于您现在块可以抛出,你将不得不改变你的函数是这样的:

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = try? {() throws in 
    // your code 
} 
+0

当我做到这一点,错误发生,但我得到的错误“呼叫可以抛出,但它没有标记'尝试',错误不处理。”这是我在我的问题中发布的函数的第一行。 –

+0

我想你需要在你的块中添加一个类型声明: – nielsbot

+0

我该如何去解决这个问题,对不起,我不明白。 –

0

尝试用catch let error as NSError更换catch

+0

当我这样做时,错误消失了,但是我收到错误“Call can throw,但它没有用'try'标记,并且错误没有被处理。”这是我在我的问题中发布的函数的第一行。 –

+0

在哪条线上出现该错误? –

+0

我在我的函数中发布的第一行。 –