Search code examples
iosswiftcore-datansfetchrequest

How to properly call fetch() on NSManagedObjectContext?


I'm in the process of learning about CoreData. I've been going through this tutorial but have run into a compilation issue in one of my UIViewControllers methods. Unless I am making an obvious mistake that is exactly what the code in the tutorial does. I'm using 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
    }
  }
}

Solution:

Earlier in my VC I declared the stores array using the wrong CoreData Entity. Fixing that mistake solved the problem.


Solution

  • Changed line

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

    To Either:

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

    Or

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