【问题标题】:No NSEntityDescriptions in any model claim the NSManagedObject subclass 'PriorityList.Entry' so +entity is confused任何模型中都没有 NSEntityDescriptions 声明 NSManagedObject 子类“PriorityList.Entry”,因此 +entity 被混淆了
【发布时间】:2025-12-15 21:35:01
【问题描述】:

我是 CoreData 的新手,我正在尝试存储待办事项列表的条目。当我尝试创建一个新条目时,它会崩溃。我的实体名称是“Entry”,我为 codegen 选择了“Extension”,但我没有在 Entry 的子类中添加任何代码。这里出了什么问题?感谢您的帮助!

    let container: NSPersistentContainer? = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer

func editOrAdd()
{
    if entry?.title != nil {
        ifNew = false   //edit entry
        updateUI()
    } else {
        ifNew = true    //new entry
        print(ifNew)

        if let context = container?.viewContext {
            let newEntry = Entry(context: context)  //crashed here
            newEntry.creatTime = Date()
            try? context.save()
            //test
            print("new entry creatTime: \(formatter((entry?.creatTime!)!))")
        }
    }
}

下面的完整日志

2020-02-14 23:06:43.471370+0800 PriorityList[8876:698237] [错误] 错误:否 任何模型中的 NSEntityDescriptions 声明 NSManagedObject 子类 'PriorityList.Entry' 所以 +实体很困惑。你已经加载了你的 NSManagedObjectModel 了吗?

2020-02-14 23:06:43.475084+0800 PriorityList[8876:698237] *** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“类“PriorityList.Entry”的 NSManagedObject 必须具有有效NSEntityDescription。'

【问题讨论】:

  • 确保核心数据设置正确,例如确保它被赋予正确的模型名称。对于codegen使用“类定义”,对于初学者来说更容易使用。

标签: swift core-data


【解决方案1】:

在观看了更多教程并完全重建我的整个项目后,问题就解决了。

我改变了

的语法
let newEntry = Entry(context: context)  //crashed here

let newItem = NSEntityDescription.insertNewObject(forEntityName: "Item", into: context) as! Item

不确定是什么问题,但确实有效。

【讨论】: