2016-03-06 92 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

我在我的函數中發佈的第一行。 –