0

My problem is that I can easily add and delete data but when I am trying to update data in Tableview did select method, when I update the last row it works fine but when I am trying to update any other row it will set the value to below row data. If any one have an answer for that then please help me for that.

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)
    }



}
jo solution
  • 401
  • 5
  • 18
  • Possible duplicate of [How do you update a CoreData entry that has already been saved in Swift?](https://stackoverflow.com/questions/26345189/how-do-you-update-a-coredata-entry-that-has-already-been-saved-in-swift) – Tamás Sengel Feb 15 '18 at 11:04
  • No it's not duplicate – jo solution Feb 15 '18 at 12:01

1 Answers1

0

You are overdoing it, no need to delete and insert a new Person object every time a change is done. Just update the attribute on the object, Core Data will take care of the rest since it already manages the object.

Something like

let selectedPerson = self.people[indexPath.row]
selectedPerson.name = ...
selectedPerson.age = ...

And then you might have to call reloadData()/reloadRows(...) on the table view

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52