gpt4 book ai didi

ios - 尝试向 Core Data 添加新记录时出错

转载 作者:搜寻专家 更新时间:2023-11-01 05:58:03 24 4
gpt4 key购买 nike

我想将数据保存到 CoreData,但出现下一个错误:

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

这是我的代码:

let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDelegate.managedObjectContext

let request: NSFetchRequest = NSFetchRequest(entityName: "UnreadMessages")
request.returnsObjectsAsFaults = false

do {
let result: NSArray = try context.executeFetchRequest(request)
let newRecord: NSEntityDescription = NSEntityDescription.entityForName("UnreadMessages", inManagedObjectContext: context)!

if result.count > 0 {
print("It exists")
print(context)
} else {
print("it's a new record")
newRecord.setValue(user.jidStr, forKey: "username")
newRecord.setValue("1", forKey: "count")

do {
try context.save()
} catch let error {
print(error)
}
print(context)
}
} catch _ {

}

直到:

print("it's a new record")
newRecord.setValue(user.jidStr, forKey: "username")

打印 It's a new record 并崩溃!我的代码有什么问题?

这是我的 CoreData 截图:

enter image description here

最佳答案

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key username.'

这是您的重要线索。这意味着您要求 NSEntityDescription 的实例使用 KVC 设置名称为“username”的属性,但该类不支持该键。

prints It's a new record and crashes! What is wrong with my code?

好吧,您的代码不会创建新的“记录”。这段代码

let newRecord: NSEntityDescription = NSEntityDescription.entityForName("UnreadMessages", inManagedObjectContext: context)!

创建一个 NSEntityDescription,它可以用来创建一个 NSManagedObject

创建一个你想调用的新“记录”

let newRecord = NSEntityDescription.insertNewObjectForEntityForName(
"UnreadMessages",
inManagedObjectContext:context)

因此,您现在可以看到您正在尝试在实体描述而非托管对象上设置“用户名”。

关于ios - 尝试向 Core Data 添加新记录时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33494431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com