将数据添加或编辑到核心数据中的现有表条目

时间:2017-10-12 18:12:39

标签: ios swift uitableview core-data

我正在尝试使用核心数据构建一个每周存储健身房客户数据的应用程序。我已设法获取我的保存按钮来存储所有客户端数据,然后在我单击用于填充表的客户端名称时显示信息。我可以删除客户端,但我无法添加或修改现有数据,这是重要的一步。我将附上我的代码和应用程​​序的屏幕截图,看看它是否有助于您了解我想要实现的目标。这是我写的代码,应该允许我添加到客户端,但是我点击第1周按钮,一切都是0.0,重量丢失,当我返回表格时,它创建了一个新的空白客户端。

ClientListViewController:

import UIKit
import CoreData

var clientItems : [Client] = []

class ClientListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {



    @available(iOS 2.0, *)
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return clientItems.count
    }

    @available(iOS 2.0, *)
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell
        let items = clientItems[indexPath.row]

        cell.textLabel?.text = items.name
        cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator

        return cell
    }

    func getData() {

        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

        do {
            clientItems = try context.fetch(Client.fetchRequest())
        } catch {
            print("Fetch Failed")
        }
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

        if editingStyle == .delete {
            let item = clientItems[indexPath.row]
            context.delete(item)
            (UIApplication.shared.delegate as! AppDelegate).saveContext()

            do {
                clientItems = try context.fetch(Client.fetchRequest())
            } catch {
                print("Fetch Failed")
            }
        }
        tableView.reloadData()
    }

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        if #available(iOS 11.0, *) {
            navigationController?.navigationBar.prefersLargeTitles = true
        } else {
            // Fallback on earlier versions
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        getData()
        tableView.reloadData()
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "segue" {

            let destinationVC = segue.destination as! ClientViewController
            let indexPath = tableView.indexPathForSelectedRow
            let client = clientItems[(indexPath?.row)!]
            destinationVC.client = client

        }
    }
}

WeekStatsViewController:

import UIKit
import CoreData

class WeekStatsViewController: UIViewController {

    var client: Client? = nil
    var managedObjectContext: NSManagedObjectContext!

    @IBOutlet weak var dobLabel: UILabel!
    @IBOutlet weak var telephoneLabel: UILabel!
    @IBOutlet weak var emailLabel: UILabel!
    @IBOutlet weak var heightLabel: UILabel!

    @IBOutlet weak var weightTextField: UITextField!
    @IBOutlet weak var weekTextField: UITextField!

    @IBOutlet weak var neckTextField: UITextField!
    @IBOutlet weak var shouldersTextField: UITextField!
    @IBOutlet weak var chestTextField: UITextField!
    @IBOutlet weak var bicepTextField: UITextField!
    @IBOutlet weak var waistTextField: UITextField!
    @IBOutlet weak var hipsTextField: UITextField!
    @IBOutlet weak var thighTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

        // Do any additional setup after loading the view.
        navigationItem.title = client!.name
        dobLabel.text = client!.dob
        telephoneLabel.text = client!.telephone
        emailLabel.text = client!.email
        heightLabel.text = String(describing: client!.height)
    }

    // Dismiss keyboard when empty space tapped
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        weightTextField.endEditing(true)
        weekTextField.endEditing(true)
        neckTextField.endEditing(true)
        shouldersTextField.endEditing(true)
        chestTextField.endEditing(true)
        bicepTextField.endEditing(true)
        waistTextField.endEditing(true)
        hipsTextField.endEditing(true)
        thighTextField.endEditing(true)
    }

    @IBAction func saveButton(_ sender: Any) {

        let editWeight = Double(weightTextField.text!)
        let editWeek = weekTextField.text
        let editNeck = Double(neckTextField.text!)
        let editShoulders = Double(shouldersTextField.text!)
        let editChest = Double(chestTextField.text!)
        let editBicep = Double(bicepTextField.text!)
        let editWaist = Double(waistTextField.text!)
        let editHips = Double(hipsTextField.text!)
        let editThigh = Double(thighTextField.text!)        

        do {

            let clientItem = Client(context: managedObjectContext)

            clientItem.setValue(editWeight, forKey: "oneWeekWeight")
            clientItem.setValue(editWeek, forKey: "weekOneSelected")
            clientItem.setValue(editNeck, forKey: "oneWeekNeck")
            clientItem.setValue(editShoulders, forKey: "oneWeekShoulders")
            clientItem.setValue(editChest, forKey: "oneWeekChest")
            clientItem.setValue(editBicep, forKey: "oneWeekBicep")
            clientItem.setValue(editWaist, forKey: "oneWeekWaist")
            clientItem.setValue(editHips, forKey: "oneWeekHips")
            clientItem.setValue(editThigh, forKey: "oneWeekThigh")

            try managedObjectContext.save()

            print("Data Saved Successfully")


        } catch {
            fatalError("Failed to fetch clients: \(error)")
        }

    }

}

这是我在运行应用时看到的步骤的屏幕截图:

enter image description here

现在编辑图像以显示正确的屏幕截图4

0 个答案:

没有答案