Swift 核心数据:在实体错误中找不到键路径

Swift core data: keypath not found in entity error

我在 swift 中获取核心数据时出错。 我的代码是这样的

var mealResultController: NSFetchedResultsController<Food>!

private func setUpMealResultController() {
    let fetchRequest: NSFetchRequest<Food> = Food.fetchRequest()
    let userPredicate = NSPredicate(format: "user == %@", User.user!)
    let sortPredicate = NSPredicate(format: "sort == %@", "meal")
    let sortDescripter = NSSortDescriptor(key: "name", ascending: false)
    fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [userPredicate, sortPredicate])
    fetchRequest.sortDescriptors = [sortDescripter]
    
    mealResultController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: dataController.viewContext, sectionNameKeyPath: nil, cacheName: nil)
    
    mealResultController.delegate = self
    do {
        try mealResultController.performFetch()
    } catch {
        fatalError("Fetch cannot be performed: \(error.localizedDescription)")
    }
}

核心数据是这样的

coredata

当我在try mealResultController.performFetch()中执行fetch时,出现了这样的错误。

2021-08-18 15:03:51.412345+0900 MealPlanner209[9647:205175] [error] error: SQLCore dispatchRequest: exception handling request: <NSSQLFetchRequestContext: 0x6000037d0d20> , keypath name not found in entity Food with userInfo of (null) CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLFetchRequestContext: 0x6000037d0d20> , keypath name not found in entity Food with userInfo of (null) 2021-08-18 15:03:51.424753+0900 MealPlanner209[9647:205175] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath name not found in entity Food'

您的错误表明您的 Food 对象没有 name。根据你的图片,如果你的 Food object

,你没有这样的 属性

我建议您使用键路径而不是字符串变量,这将允许您在构建时出错而不是在运行时崩溃:

let key = NSExpression(forKeyPath: \Food.name).keyPath
let sortDescripter = NSSortDescriptor(key: key, ascending: false)