如何在 NSManagedObjectContext 上正确调用 fetch()?

How to properly call fetch() on NSManagedObjectContext?

我正在学习 CoreData。我一直在经历 this tutorial 但 运行 在我的 UIViewController 方法之一中遇到了编译问题。除非我犯了一个明显的错误,这正是本教程中的代码所做的。我正在使用 Xcode 8.2.1.

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 数组。修正那个错误解决了问题。

换行

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

至:

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

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