我有一个名为“Users”的实体,具有两个名为“用户名”和“密码”的属性。
我有另一个名为“Info”的实体,有 4 个名为“avatar”、“level”、“loss”、“win”的属性。
我与名为“用户”的实体建立了关系 “用户信息” 目的地:“信息” 反向:“用户详细信息”
我与名为“Info”的实体建立了关系 “用户详细信息” 目的地:“用户” 逆:“用户信息”
这是我现在的代码:
@IBAction func loginButtonPressed(_ sender: UIButton) {
// getting the inputs from the user
let username = usernameField.text!
let userPassword = passwordField.text!
// creating a request to fetch the results for the users
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
request.returnsObjectsAsFaults = false
// now getting all the results
do
{
// saving results in results
let results = try context.fetch(request)
// now checking if there is any results
if results.count > 0
{
// creating a for loop to go through the results
for result in results as! [NSManagedObject]
{
// checking if username and password match
if username == (result.value(forKey: "username") as? String)! && userPassword == (result.value(forKey: "password") as? String)!
{
// if they do set "isLoggedIn" to true
UserDefaults.standard.set(true, forKey:"isLoggedIn")
UserDefaults.standard.synchronize()
// Now saving the username and info of the user to the main viewController to display the users data later
// I NEED TO SAVE FROM THE RELATIONSHIP DATA HERE
// dismissing this view to go to the main view
self.dismiss(animated: true, completion: nil)
}
else
{
// if username and passwords dont match then display it to the user.
alertMessage(userMessage: "Login failed username or password do not match!")
}
}
}
else
{
// if no results then display error message
alertMessage(userMessage: "Login Failed: No users registered!")
}
}
catch
{
// catch
}
}
检查用户名和密码是否正确后,我需要将该用户名和密码的关系数据存储到 4 个变量中。命名为:胜利、失败、等级和头像。
我对如何从关系中获取正确的数据感到困惑
我尝试使用“结果”变量来尝试获得此结果,但没有成功。
谢谢
最佳答案
人们通常会创建代表实体的类,而不是直接将实体作为 NSManagedObjects
使用,所以这看起来有点奇怪。但您应该能够使用 setValueForKey:
result.setValue(/* whatever */, forKey: "userInfo.avatar")
关于swift - 如何从核心数据中的关系中获取值(swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43745176/