简体   繁体   中英

Error in Fetch: “Cannot convert value of type 'NSFetchRequest<NSManagedObject>' to expected argument type 'NSFetchRequest<NSFetchRequestResults>'”

Using this function to sort my cells in my table view. I am getting an error in my fetch request. The line inside of the do loop, notes = try context.fetch(request) is causing the error , the request is underlined

The error says "Cannot convert value of type 'NSFetchRequest' to expected argument type 'NSFetchRequest'"

My TableViewController file

 import UIKit
import CoreData


class noteTableViewController: UITableViewController {

    var notes = [Note]()

    var managedObjectContext: NSManagedObjectContext? {

        return (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    }


    func loadDataFromDatabase() {

        let settings = UserDefaults.standard

        let sortPriority = settings.string(forKey: Constants.kPriority)

        let context = appDelegate.persistentContainer.viewContext

        let request = NSFetchRequest<NSManagedObject>(entityName: "Note")

        let sortDescriptor = NSSortDescriptor(key: sortPriority)

        let sortDescriptorsArray = [sortDescriptor]

        request.sortDescriptors = sortDescriptorsArray

        do {

            notes = try context.fetch(request)
        } catch let errer as NSError {

            print("Could not fetch. \(error), \(error.userInfo)")
        }


    }


}

You need to cast it as an array of Notes

  do {
    notes = try context.fetch(request) as? [Note] ?? []
  } catch let errer as NSError {
    print("Could not fetch. \(error), \(error.userInfo)")
  }

Try this:

func loadDataFromDatabase() {
  ...

  let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Note")

  ...

  do {
    notes = try context.fetch(request) as? [Note] ?? []
  } catch let errer as NSError {
    print("Could not fetch. \(error), \(error.userInfo)")
  }
}

Of course, I'm assuming your Note class is a subclass of NSManagerObject .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM