我不确定我在做什么错了:/

我想要的是能够通过给定名称获取存储在实体内核心数据属性中的所有数据。

因此,例如,存储了有关用户“ 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:]:实体Users不符合键“ James”的编码键值。


有任何想法吗?

P.s.这在一个名为UserDetails的类中。在该类的函数之前但仍在该类范围内的我已设置:

let jsonLocation = "https://link.to/json/for/users"
let appDelegate = UIApplication.shared.delegate as! AppDelegate

最佳答案

方法getUserDetails()导致此问题。

在行中

print(data.value(forKey: name) as! String)


您正在获取传递的参数字符串的属性(而不是文字"name"),但是模型中没有属性James

您必须添加一个谓词以过滤nameJames的记录,并输出文字字符串"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)
    }
}

关于swift - 'NSUnknownKeyException',原因:'[<Users 0x78eb5bf0> valueForUndefinedKey:]:实体Users不符合键“James”的键值编码要求。,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48029791/

10-14 22:10