Swift - данные не отображаются в TableView после извлечения их из UserDefaults - PullRequest
0 голосов
/ 15 сентября 2018

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

В настоящее время я сохраняю его в первом контроллере представления:

let userEntry = UserEntries(date: String(todayDate), questions: [UserEntries.Question(question: q1Text, answer: q1Answer), UserEntries.Question(question: q2Text, answer: q2Answer)])

    var allEntries : [UserEntries] = []
    if doesKeyExist(key: "allEntries") == true {
        let jsonDecoder = JSONDecoder()
        if let data = UserDefaults.standard.data(forKey: "allEntries"),
            let userEntries = try? jsonDecoder.decode(UserEntries.self, from: data) {
            allEntries = [userEntries]
        }

        allEntries.insert(userEntry, at: 0)

        let jsonEncoder = JSONEncoder()
        if let value = try? jsonEncoder.encode(allEntries) {
            UserDefaults.standard.set(value, forKey: "allEntries")
            UserDefaults.standard.synchronize()
        }
    } else {
        let jsonEncoder = JSONEncoder()
        if let value = try? jsonEncoder.encode(userEntry) {
            UserDefaults.standard.set(value, forKey: "allEntries")
            UserDefaults.standard.synchronize()
        }
    }

    let newViewController = storyboard?.instantiateViewController(withIdentifier: "tabViewController") as! UITabBarController
    present(newViewController, animated: true, completion: nil)
}

Вот как я отображаю это в TableView

var TableData : [UserEntries] = []
override func viewDidLoad() {
    super.viewDidLoad()

    let jsonDecoder = JSONDecoder()
    if let data = UserDefaults.standard.data(forKey: "allEntries"),
        let userEntries = try? jsonDecoder.decode(UserEntries.self, from: data) {
        print(userEntries.date)
        TableData = [userEntries]
    }

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem
}

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

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

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "entryCell", for: indexPath)

    cell.textLabel?.text = TableData[indexPath.row].date
    cell.detailTextLabel?.text = TableData[indexPath.row].questions[0].answer

    return cell
}

У меня такое ощущение, что это логическая ошибка при получении / отображении данных в TableView, но я не уверен, что именноесть / как это исправить.Спасибо за вашу помощь!

1 Ответ

0 голосов
/ 15 сентября 2018

Я не знаю, что делает ваша doesKeyExists функция, но вы можете улучшить ваши манипуляции с данными следующим образом:

    let userEntry = UserEntries(date: String(todayDate), questions: [UserEntries.Question(question: q1Text, answer: q1Answer), UserEntries.Question(question: q2Text, answer: q2Answer)])

    var allEntries : [UserEntries] = []

    let jsonDecoder = JSONDecoder()
    if let data = UserDefaults.standard.data(forKey: "allEntries"),
         let userEntries = try? jsonDecoder.decode([UserEntries].self, from: data) {
        allEntries = userEntries
    }

    allEntries.insert(userEntry, at: 0)

    let jsonEncoder = JSONEncoder()
    if let value = try? jsonEncoder.encode(allEntries) {
        UserDefaults.standard.set(value, forKey: "allEntries")
        UserDefaults.standard.synchronize()
    }

    let newViewController = storyboard?.instantiateViewController(withIdentifier: "tabViewController") as! UITabBarController
    present(newViewController, animated: true, completion: nil)
}

И проблема с вашим контроллером в том, что вы сохраняете только одну запись в UserDefaults. Попробуйте изменить свой код на

let jsonDecoder = JSONDecoder()
if let data = UserDefaults.standard.data(forKey: "allEntries"),
    let userEntries = try? jsonDecoder.decode([UserEntries].self, from: data) {
    print(userEntries)
    TableData = userEntries
}
...