Удалить не работает и последнее значение не отображается, Пользователь по умолчанию с табличным представлением - PullRequest
0 голосов
/ 20 мая 2019

Я реализовал сохранение данных локально, используя пользовательские настройки по умолчанию с табличным представлением. при вставке данных все данные отображаются в моем табличном представлении. но остановитесь и запустите снова, последнее значение не отображается. и когда смахивание и удаление не работает, когда приложение запускается в следующий раз.

import UIKit
let defaults = UserDefaults(suiteName: "com.saving.data")

class HomeWorkViewController: UITableViewController {

    var rows = [String]()

вызов метода getData () в viewDidload

    override func viewDidLoad() {
        super.viewDidLoad()
        getData()
        // Do any additional setup after loading the view.
        self.navigationItem.rightBarButtonItem = self.editButtonItem
    }

вызов метода getData ()

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

вызов метода storeData

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

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func addButton(_ sender: Any) {
        addCell()
    }
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "homeWork", for: indexPath)
        cell.textLabel?.text = rows[indexPath.row]
        return cell
    }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            rows.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)
            tableView.reloadData()
        }else if editingStyle == .insert {

        }
    }

    func addCell(){
        let alert = UIAlertController(title: "Add Home Work", message: "Input text", preferredStyle: .alert)
        alert.addTextField{(textField) in
    textField.placeholder = "text...."
        }
        alert.addAction(UIAlertAction(title: "Confirm", style: .default, handler: {[weak alert](_) in
            let row = alert?.textFields![0]
            self.rows.append((row?.text)!)
            self.tableView.reloadData()
        }))
        self.present(alert,animated: true, completion: nil)
        storeData()
    }

    func storeData(){
        defaults?.set(rows, forKey: "savedData")
        defaults?.synchronize()
    }


    func getData(){
     let data = defaults?.value(forKey: "savedData")
        if data != nil {
            rows = data as! [String]
        }else{}
    }
}

1 Ответ

1 голос
/ 20 мая 2019

Вы звоните storeData() в неправильном месте. Закрытие addAction выполняется позже.

func addCell() {
    let alert = UIAlertController(title: "Add Home Work", message: "Input text", preferredStyle: .alert)
    alert.addTextField{(textField) in
        textField.placeholder = "text...."
    }
    alert.addAction(UIAlertAction(title: "Confirm", style: .default, handler: {[weak alert](_) in
        let row = alert?.textFields![0]
        let insertionIndex = self.rows.count
        self.rows.append(row.text!)
        self.tableView.insertRows(at: IndexPath(row: insertionIndex, section: 0), with: .automatic)
        self.storeData()
    }))
    self.present(alert,animated: true, completion: nil)
}

И никогда не звоните reloadData после звонка deleteRows

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        rows.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
        self.storeData()
    }
}

И используйте специальный API UserDefaults (не звоните synchronize)

func storeData(){
    defaults!.set(rows, forKey: "savedData")
}


func getData(){
    rows = defaults!.array(forKey: "savedData") as? [String] ?? []
}
...