1

Ive been attempting to save cells that are added into a TableView once the app is closed. Whenever the app is reloaded or reopened the added cells are deleted.

This is my function to insert a cell when a button is tapped:

func insertMessageInRow() {

    messages.append(MessageTextField.text!)

    let indexPath = IndexPath(row: messages.count - 1, section: 0)
    UserDefaults.standard.didChangeValue(forKey: "Save")
    SavedMessages.beginUpdates()
    SavedMessages.insertRows(at: [indexPath], with: .fade)
    SavedMessages.endUpdates()

    MessageTextField.text = ""
    view.endEditing(true)

    let defaults = UserDefaults.standard
    defaults.set(messages, forKey: "Save")

}

This is my code or the TableView to insert the cell and change the label:

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

    let defualts = UserDefaults.standard
    let stingArray = defualts.stringArray(forKey: "Save") ?? [String]()

    let message = stingArray[indexPath.row]

    let cell = SavedMessages.dequeueReusableCell(withIdentifier: "MessageCell") as! TableViewCell
    cell.MessageLable.text = message

    return cell
}

I can't seem to get the table to save anything when the app is closed. I've looked around the internet for days now on how to accomplish this. Thanks in advance!

Alaeddine
  • 6,104
  • 3
  • 28
  • 45
Carter Cobb
  • 790
  • 7
  • 13

0 Answers0