简体   繁体   中英

UserDefault Won't save data in tableView Swift 4

I have been trying to save data when reloading app. However some how data won't save.

my global variable

let defaults = UserDefaults.standard

this is my code on AddTaskView

@IBAction func addTask(_ sender: Any) {

    let date = datePicker.date

    let dateStr = dateFormatter.string(from: date)

    taskArray.append(selectedTask)
    dateArray.append(dateStr)

    defaults.set(selectedTask, forKey: "task")
    defaults.set(dateStr, forKey: "date")

    dismiss(animated: true, completion: nil)
}

In my ViewController I have my viewWillApper

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    defaults.string(forKey: "task")
    defaults.string(forKey: "date")

    tableView.reloadData()
}

If I print the data coming back from AddTaskView It will print on console but data disappear when reloading app

tableView.dataSource = self (saved in my viewDidLoad)

this is my tableView

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "taskCell", for: indexPath)

    cell.textLabel?.text = "\(indexPath.row + 1). \(taskArray[indexPath.row])"

    cell.detailTextLabel?.text = dateArray[indexPath.row]

    return cell
}

What Am I doing wrong?

thanks

You have multiple checks to do:

  1. defaults.string(forKey: "task") has a return value that you dont use

  2. As you append entered data, check if its has been append.

  3. If entered value is there, check count of rows of the table.

I believe the key to solve your problem is in one of these points.

Took me a while but I finally figured

@IBAction func addTask(_ sender: Any) {

    let date = datePicker.date

    let dateStr = dateFormatter.string(from: date)

    taskArray.append(selectedTask)
    dateArray.append(dateStr)

    defaults.set(taskArray, forKey: "task")
    defaults.set(dateArray, forKey: "date")
    defaults.synchronize()

    dismiss(animated: true, completion: nil)
}

func loadUserDefaults() {
    if let tempStr = defaults.stringArray(forKey: "task") {



        taskArray = tempStr as [String]

    }

    if let tempDateStr = defaults.stringArray(forKey: "date") {



        dateArray = tempDateStr as [String]

    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.dataSource = self
    loadUserDefaults()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM