我不确定我在这里做错了什么:/
我想要的是能够通过给定名称获取存储在实体内的核心数据属性中的所有数据。
例如,存储有关用户“James”的所有信息。
这是我的代码:
func getUserDetails(name: String) {
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
for data in result as! [NSManagedObject] {
print(data.value(forKey: name) as! String)
}
} catch {
print("Failed")
}
}
我正在设置此信息:
func parseJson() {
let context = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Users", in: context)
let user = NSManagedObject(entity: entity!, insertInto: context)
Alamofire.request(jsonLocation).responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
for (_, value) in swiftyJsonVar {
let name = value["name"].stringValue
let gender = value["gender"].stringValue
let age = value["age"].intValue
user.setValue(name, forKey: "name")
user.setValue(gender, forKey: "gender")
user.setValue(age, forKey: "age")
do {
try context.save()
} catch {
print("Failed saving")
}
}
}
}
}
但我得到的错误是:
'NSUnknownKeyException',原因:'[valueForUndefinedKey:]:实体用户对密钥“James”不符合密钥值编码。'
有什么想法吗?
P.S。这是一个名为UserDetails的类。在类的函数之前,但仍然在我设置的类范围:
let jsonLocation = "https://link.to/json/for/users"
let appDelegate = UIApplication.shared.delegate as! AppDelegate
答案 0 :(得分:0)
方法getUserDetails()
会导致问题。
在第
行print(data.value(forKey: name) as! String)
您获取传递的参数字符串的属性(而不是文字"name"
),但模型中没有属性James
。
您必须添加谓词来过滤name
为James
的记录,并打印文字字符串"name"
的值
func getUserDetails(name: String) {
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
request.predicate = NSPredicate(format: "name == %@", name)
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request) as! [NSManagedObject]
for data in result {
print(data.value(forKey: "name") as! String)
}
} catch {
print(error)
}
}
注意:
强烈建议使用NSManagedObject
子类来更方便地访问属性。它避免了这种错误。我还建议使用更多描述性变量名称。
func getUserDetails(name: String) {
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<Users>(entityName: "Users")
request.predicate = NSPredicate(format: "name == %@", name)
request.returnsObjectsAsFaults = false
do {
let users = try context.fetch(request)
for user in users {
print(user.name)
}
} catch {
print(error)
}
}