我无法使用swift 3.0编辑数据并将数据保存到核心数据中?

时间:2017-04-20 04:13:33

标签: ios swift core-data swift3

这里我已经完成了保存数据并在表视图上显示它也已经完成但问题是我无法编辑和更新数据到核心数据库可以有人帮助我吗?

@IBAction func updateButtonClicked(_ sender: Any) {
            var firstname = ""
            var lastname = ""
            var emailid = ""
            var Password = ""
            var mobileNumber = ""

            firstname = firstnameTextfield.text!
            lastname = lastanameTextField.text!
            emailid = emailidTextField.text!
            Password = passwordTextField.text!
            mobileNumber = mobilenumberTextField.text!

            let appDelegate = UIApplication.shared.delegate as! AppDelegate
            let managedContext = appDelegate.persistentContainer.viewContext
            let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:"Account")
            do {
                let list = try context.fetch(fetchRequest) as? [NSManagedObject]
                if list?.count != 0
                {
                    let newManagedObject = NSEntityDescription.insertNewObject(forEntityName: "Account", into: context)
                    newManagedObject.setValue(firstnameTextfield.text, forKey: "firstName")
                    newManagedObject.setValue(lastanameTextField.text, forKey: "lastname")
                    newManagedObject.setValue(emailidTextField.text, forKey: "emailID")
                    newManagedObject.setValue(passwordTextField.text, forKey: "password")
                    newManagedObject.setValue(mobilenumberTextField.text, forKey: "mobileNumber")
                    try managedContext.save()
                }
                }
            catch let error as NSError {
                print("Fetch failed: \(error.localizedDescription)")
            }

1 个答案:

答案 0 :(得分:0)

在您的代码中,您可以混合获取数据和插入新数据。请检查这些答案:

https://stackoverflow.com/a/28258374/4689446

https://stackoverflow.com/a/38423458/4689446

如何更新核心数据中的现有对象的一般想法:

  • 使用谓词
  • 获取数据
  • 你找回匹配对象的数组
  • 设置这些对象的值并将其保存回来