如何使用Core Data更新数据?

时间:2018-02-15 10:59:37

标签: ios swift uitableview core-data

我的问题是我可以轻松添加和删除数据但是当我尝试更新Tableview中的数据时确实选择了方法,当我更新最后一行它工作正常但是当我尝试更新任何其他行时它将设置以下行数据的值。如果有人对此有答案,那么请帮助我。

import UIKit
import CoreData

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!


    var people = [Person]()

    override func viewDidLoad() {
        super.viewDidLoad()
        let fetchRequest: NSFetchRequest<Person> = Person.fetchRequest()

        do {
            let people = try PersistenceServce.context.fetch(fetchRequest)
            self.people = people
            self.tableView.reloadData()
        } catch {}
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBAction func onPlusTapped() {
        let alert = UIAlertController(title: "Add Person", message: nil, preferredStyle: .alert)
        alert.addTextField { (textField) in
            textField.placeholder = "Name"
        }
        alert.addTextField { (textField) in
            textField.placeholder = "Age"
            textField.keyboardType = .numberPad
        }
        let action = UIAlertAction(title: "Post", style: .default) { (_) in
            let name = alert.textFields!.first!.text!
            let age = alert.textFields!.last!.text!
            let person = Person(context: PersistenceServce.context)
            person.name = name
            person.age = Int16(age)!
            PersistenceServce.saveContext()
            self.people.append(person)
            self.tableView.reloadData()
        }
        alert.addAction(action)
        present(alert, animated: true, completion: nil)
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return people.count

    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .subtitle, reuseIdentifier: nil)
        cell.textLabel?.text = people[indexPath.row].name
        cell.detailTextLabel?.text = String(people[indexPath.row].age)
        return cell

    }
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        let person = people[indexPath.row]
        if editingStyle == .delete  {
            PersistenceServce.context.delete(person)
            PersistenceServce.saveContext()
            people.remove(at: indexPath.row)
            self.tableView.deleteRows(at: [indexPath], with: .automatic)
        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let alert = UIAlertController(title: "Update Person", message: nil, preferredStyle: .alert)
        alert.addTextField { (textField) in
            textField.text = self.people[indexPath.row].name
        }
        alert.addTextField { (textField) in
            textField.text = String(self.people[indexPath.row].age)
            textField.keyboardType = .numberPad
        }
        let action = UIAlertAction(title: "Update", style: .default) { (_) in

        let name = alert.textFields!.first!.text!
        let age = alert.textFields!.last!.text!
            print(self.people)


            PersistenceServce.context.delete(self.people[indexPath.row])
            print(self.people)

            let person = Person(context: PersistenceServce.context)
            person.name = name
            person.age = Int16(age)!
            self.people.append(person)
            self.people.remove(at: indexPath.row)

            print(self.people)
            self.tableView.reloadRows(at: [indexPath], with: .automatic)
            PersistenceServce.saveContext()

        }
        alert.addAction(action)
        present(alert, animated: true, completion: nil)
    }



}

1 个答案:

答案 0 :(得分:0)

您过度使用它,无需在每次更改时删除并插入新的Person对象。只需更新对象上的属性,Core Data将负责其余部分,因为它已经管理了对象。

这样的东西
let selectedPerson = self.people[indexPath.row]
selectedPerson.name = ...
selectedPerson.age = ...

然后你可能不得不在表视图上调用reloadData()/ reloadRows(...)