如何使用 userdefault Swift 4 存储和检索表数据

How to store and retrieve tabledata using userdefault Swift 4

我的任务是用户 data 使用 strut 方法附加到 items 数组并分配给 tableView table 数据 array。在我的代码中,我在多个地方使用了 tableData 一些 validations.

现在,我的问题是,当我将 background 移动到 foreground 时,我可以看到我的 table 数据,但是如果我从 background 中删除应用程序,那么如果我打开我的application,有emptytable视图。所以,我需要明白。如何将table数据store导入UserDeafult,然后retrieve加载table视图以避免data丢失。

// Array declaration
var items = [Item]()
var tableData = [Item]() 

public func documentPicker(_ controller: UIDocumentPickerViewController,didPickDocumentsAt urls: [URL]) {

    // Here I am getting user selected file url and its name from iCloud.
    // I skipped to paste here.

    // User picked file data appending into items array
    items.append(Item(url: bookurl, title: name))

    // Assign items data to tableData
    if let data = UserDefaults.standard.data(forKey:"items") {
        do {
            let itemsUser = try PropertyListDecoder().decode(Array<Item>.self, from: data)
                tableData = itemsUser
        } catch { print(error) }
    }
}  

// MARK - TABLE VIEW DELEGATIONS
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return self.tableData.count
}

// TableView data-load 
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomTableViewCell
    let item = tableData[indexPath.row]
        cell.name_label.text = item.name
    }
   return cell
}

对于上述情况 UserDefault 应该是 picker delegationoutside。如果我们在 viewDidload 内维护一些 logic 那么它会很好地工作。

//Within ViewDidLoad
 if let data = UserDefaults.standard.data(forKey:"items") {
        do {
            let itemsUser = try PropertyListDecoder().decode(Array<Item>.self, from: data)
                tableData = itemsUser
        } catch { print(error) }
    }