繁体   English   中英

获取时出错:“无法转换类型&#39;NSFetchRequest的值 <NSManagedObject> &#39;到预期的参数类型&#39;NSFetchRequest <NSFetchRequestResults> “”

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

使用此函数在表视图中对单元格进行排序。 我在获取请求中收到错误。 do循环内部的行, notes = try context.fetch(request)导致错误,请求带有下划线

错误显示“无法将类型'NSFetchRequest'的值转换为预期的参数类型'NSFetchRequest'”

我的TableViewController文件

 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)")
        }


    }


}

您需要将其转换为Notes数组

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

尝试这个:

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)")
  }
}

当然,我假设你的Note类是NSManagerObject的子NSManagerObject

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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