2017-03-09 38 views
0

我正在學習CoreData的過程。我一直在經歷this tutorial,但在我的一個UIViewController的方法中遇到了編譯問題。除非我犯了一個明顯的錯誤,這正是教程中的代碼。我使用Xcode 8.2.1。如何在NSManagedObjectContext上正確調用fetch()?

func getStores() { 
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } 
    let managedContext = appDelegate.persistentContainer.viewContext 
    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Store") 

    do { 
     // Compilation error on the next line: 
     // Cannot convert value of type 'NSFetchRequest<Store>' to expected argument type 'NSFetchRequest<NSFetchRequestResult> 
     stores = try managedContext.fetch(fetchRequest) 
    } catch { 
     // handle error 
    } 
    } 
} 

解決方案:

在我的VC早些時候我聲明使用了錯誤的CoreData實體的stores陣列。解決這個錯誤解決了這個問題。

+0

如果'stores'與類型定義'[存儲]'那麼你可能會得到與'fetch'的調用不匹配,在你的情況下我相信''[NSManagedObject]' - 你得到的實際錯誤信息是什麼? – MathewS

回答

1

變更線

let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Store") 

要麼:

let fetchRequest: NSFetchRequest<NSFetchRequestResult> = Store.fetchRequest() 

或者

let fetchRequest = NSFetchRequest<Store>(entityName: "Store") 
+0

奇怪。即使使用這些更改我仍然會得到相同的錯誤([截圖](https://www.evernote.com/l/ABMAeVYIpdxGc66qj7CXMZ53y8c8pxTdLKUB/image.png) – RobertJoseph

+1

@RobertJoseph嘗試清理生成項目,因爲這是完美的工作 –

+0

我試過了,我甚至從DerivedData文件夾中刪除了項目,出現了一些奇怪的事情,謝謝你的幫助,我將這個標記爲已解決,因爲我確定你是對的 – RobertJoseph

相關問題