我想将数据保存到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截图:
答案 0 :(得分:4)
因未捕获的异常终止应用&#39; NSUnknownKeyException&#39;, 原因:&#39; [ setValue:forUndefinedKey:]:此类不是键值 符合编码的密钥用户名。&#39;
这是你的大线索。这意味着您要求NSEntityDescription
的实例使用KVC设置名称为&#34; username&#34;但那个班不支持那个键。
打印出新记录并崩溃!我的代码出了什么问题?
嗯,您的代码不会创建新的&#34;记录。&#34;这段代码
let newRecord: NSEntityDescription = NSEntityDescription.entityForName("UnreadMessages", inManagedObjectContext: context)!
创建NSEntityDescription
,可用于创建NSManagedObject
。
创建一个新的&#34;记录&#34;你想打电话
let newRecord = NSEntityDescription.insertNewObjectForEntityForName(
"UnreadMessages",
inManagedObjectContext:context)
因此,您现在可以看到您正在设置&#34;用户名&#34;在实体描述上,而不是托管对象。
答案 1 :(得分:2)
我认为如果找不到匹配的记录,首先需要插入托管对象上下文...
do {
let result: NSArray = try context.executeFetchRequest(request)
if result.count > 0 {
// NEW CODE: Print the username if found in result[0]
let userFound = result[0]
let usernamefound = String(userFound.valueForKey("username")!)
print("It exists \(usernameFound)")
print(context)
} else {
print("it's a new record")
let newRecordEntity: NSEntityDescription = NSEntityDescription.entityForName("UnreadMessages", inManagedObjectContext: context)!
let newRecord = UnreadMessages(entity: newRecordEntity!, insertIntoManagedObjectContext: context)
newRecord.setValue(user.jidStr, forKey: "username")
newRecord.setValue("1", forKey: "count")
do {
try context.save()
} catch let error {
print(error)
}