【问题标题】:Error: "this class is not key value coding-compliant" - for any key错误:“此类不符合键值编码” - 对于任何键
【发布时间】:2019-06-27 01:24:16
【问题描述】:

我在 Core Data 模型中保存了一个对象,但我发现该键与任何键都不兼容。

我尝试颠倒键的顺序,但我得到了任何结果,我尝试更改 nome o 实体但也没有用。

        let mediaEntity = NSEntityDescription.entity(forEntityName: 
"Media", in: managedContext)
        mediaEntity?.setValue(showMediaModel.popularity, forKey: "popularity")
        mediaEntity?.setValue(showMediaModel.title, forKey: "title")
        mediaEntity?.setValue(showMediaModel.type.rawValue, forKey: "type")
        mediaEntity?.setValue(showMediaModel.id, forKey: "id")

        do {
            try managedContext.save()
        } catch let error as NSError {
            print("Could not save. \(error), \(error.userInfo)")
        }

核心数据模型:

详细信息错误是:

Terminating app due to uncaught exception 'NSUnknownKeyException', 
reason: '[<NSEntityDescription 0x6000008c02c0> 
setValue:forUndefinedKey:]: this class is not key value coding- 
compliant for the key popularity.'

我在启动项目后按照本教程添加了核心数据:https://welcm.uk/blog/adding-core-data-to-an-existing-project-in-xcode-10-swift-4

【问题讨论】:

  • 我忘了我添加到 NSManagedObject,而不是 NSEntityDescription。谢谢!

标签: swift core-data


【解决方案1】:

检查您的xcdatamodel 文件并确保您的“popularity”拼写与出现错误的行中的拼写匹配。

【讨论】:

  • 它对任何键都不起作用,我检查了每个键的名称。
【解决方案2】:

我忘记创建对象了。

if let mediaEntity = NSEntityDescription.entity(forEntityName: "Media", in: managedContext) {
    let newEntity = NSManagedObject(entity: mediaEntity, insertInto: managedContext)
    newEntity.setValue(showMediaModel.popularity, forKey: "popularity")
    newEntity.setValue(showMediaModel.title, forKey: "title")
    newEntity.setValue(showMediaModel.type.rawValue, forKey: "type")
    newEntity.setValue(showMediaModel.id, forKey: "id")

    do {
        try managedContext.save()
    } catch let error as NSError {
        print("Could not save. \(error), \(error.userInfo)")
    }
}

【讨论】:

    猜你喜欢
    • 2019-06-23
    • 2017-10-24
    • 2017-12-23
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多