[英]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 do循环内部的行, notes = try context.fetch(request)
导致错误,请求带有下划线
The error says "Cannot convert value of type 'NSFetchRequest' to expected argument type 'NSFetchRequest'" 错误显示“无法将类型'NSFetchRequest'的值转换为预期的参数类型'NSFetchRequest'”
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 您需要将其转换为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
. 当然,我假设你的Note
类是NSManagerObject
的子NSManagerObject
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.