尝试存储数据时代码出错

时间:2019-11-22 07:05:45

标签: ios swift

我知道

  

在“数组”上引用实例方法“编码​​”要求“((项目:字符串?,价格:字符串?,销售价格:字符串?)”)符合“可编码”“

storeData()函数中的此错误。我什至没有正确保存用户默认的元组?如果有人可以帮助,那就太好了!感谢您的帮助!

import UIKit

let defaults = UserDefaults(suiteName: "com.Saving.Data")

struct Product: Codable {
    var title: String
    var price: String
    var salePrice: String
}

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    var items: [(item: String?, price: String?, salesPrice: String?)] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        getData()
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        getData()
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(true)
        storeData()
    }
    override var prefersStatusBarHidden: Bool {
        return true
    }

    @IBAction func addButtonTapped(_ sender: Any) {
        let alert = UIAlertController(title: "Product Information", message: nil, preferredStyle: .alert)
            alert.addTextField { (itemTF) in
                itemTF.placeholder = "Item"
            }

            alert.addTextField { (textField) in
                textField.placeholder = "Price"
            }

            alert.addTextField { (textField) in
                textField.placeholder = "Sale Price"
            }

            let action = UIAlertAction(title: "Add", style: .default) { (_) in

                var product : (item: String, price: String, salesPrice: String) = ("","","")

                if let textField1 = alert.textFields?[0], let text = textField1.text {
                    print(text)
                    product.item = text

                }

                if let textField2 = alert.textFields?[1], let text = textField2.text {
                    print(text)
                     product.price = text

                }

                if let textField3 = alert.textFields?[2], let text = textField3.text {
                    print(text)
                    product.salesPrice = text

                }
                self.add(product)
            }

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

       func add(_ product: (item: String, price: String, salesPrice: String)) {
            let index = 0
            items.insert(product, at: index)

            let indexPath = IndexPath(row: index, section: 0)
            tableView.insertRows(at: [indexPath], with: .left)
            storeData()
        }


     func storeData() {

           if let data = try? PropertyListEncoder().encode(items) {
            UserDefaults.standard.set(data, forKey: "savedData")

           }
       }

       func getData() {

        if let data = UserDefaults.standard.data(forKey: "savedData") {
            let items = try! PropertyListDecoder().decode([Product].self, from: data)
            print(items)
           }
       }



}

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

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = UITableViewCell()
        let product = items[indexPath.row]
        cell.textLabel?.text = product.item
        print(product.price ?? "")
        print(product.salesPrice ?? "")

        cell.contentView.backgroundColor = UIColor(red:0.92, green:0.92, blue:0.92, alpha:1.0)
        cell.textLabel?.textColor = UIColor(red:0.13, green:0.13, blue:0.13, alpha:1.0)
        tableView.separatorColor = UIColor(red:0.92, green:0.92, blue:0.92, alpha:1.0)


        return cell
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        guard editingStyle == .delete else { return }
        items.remove(at: indexPath.row)
        tableView.reloadData()
        storeData()
    }
}

1 个答案:

答案 0 :(得分:0)

正如注释中已经提到的,为什么使用结构与结构Product相同的额外元组是令人难以理解的。这会导致您的问题。

因此摆脱元组。

声明items

var items = [Product]()

将警报操作替换为

let action = UIAlertAction(title: "Add", style: .default) { _ in

    let item = alert.textFields?[0].text ?? ""
    let price = alert.textFields?[1].text ?? ""
    let salesPrice = alert.textFields?[2].text ?? ""

    let product = Product(item: item, price: price, salesPrice: salesPrice)
    self.addProduct(product)
}

add替换为

  func addProduct(_ product: Product) {
        let index = 0
        items.insert(product, at: index)

        let indexPath = IndexPath(row: index, section: 0)
        tableView.insertRows(at: [indexPath], with: .left)
        storeData()
    }

getData替换为

func getData() {
    if let data = UserDefaults.standard.data(forKey: "savedData") {
        do {
            items = try PropertyListDecoder().decode([Product].self, from: data)
            print(items)
            tableView.reloadData()
        } catch { print(error) }
    }
}

旁注:请注意,代码会将数据保存在标准 UserDefaults中,而不是保存在自定义套件中。

最后-与问题无关-在tableView:commit editingStyle:替换中获得漂亮的动画

tableView.reloadData()

使用

tableView.deleteRows(at: [indexPath], with: .fade)