Tableview reloadData 不适用于显示 NSUserDefaults 数组的 tableView

Tableview reloadData not working with tableView displaying array of NSUserDefaults

我有一个 tableView,它显示 array 个已存储的 NSUserDefaults。在尝试删除其中一行时,我能够更新我存储的默认值的数组,但这并没有反映在 tableView 中。

简而言之,tableview.reloadData 由于某种原因没有重新加载我的 tableView

下面是我在 UIViewController

中调用 usedefaults 的代码
   override func viewDidAppear(_ animated: Bool) {
    encodedData = UserDefaults.standard.object(forKey: "newSave") as? NSData
    saveArticlesArray = (NSKeyedUnarchiver.unarchiveObject(with: encodedData! as Data) as? [SaveArticle])!
    offTableView.reloadData()
}

//populating the table

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCell(withIdentifier: "OfflineCell", for: indexPath) as! OfflineTableViewCell
   cell.offTitle.text = saveArticlesArray[indexPath.row].saveTitle
    return cell
}

//Deleting a row and its related stored userdefault

   func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == UITableViewCellEditingStyle.delete{
         var tempArray: [AnyObject] = saveArticlesArray as [AnyObject]
        tempArray.remove(at: indexPath.row)
        DispatchQueue.main.async{
            print("reached dispacth")
            //self.offTableView.reloadData()
            tableView.reloadData()
        }

        encodedData = NSKeyedArchiver.archivedData(withRootObject: tempArray) as NSData
        UserDefaults.standard.set(encodedData, forKey: "newSave")
        UserDefaults.standard.synchronize()
    }    
}

请注意,当我关闭并重新打开 ViewController 时,所选行的值确实会被删除。我只需要重新加载 tableView 以便用户可以看到该行已被删除。

用这个方法替换你的方法 tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) 希望这能解决你的问题。

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == UITableViewCellEditingStyle.delete{
        saveArticlesArray.remove(at: indexPath.row)
        DispatchQueue.main.async{
            print("reached dispacth")
            //self.offTableView.reloadData()
            tableView.reloadData()
        }

        encodedData = NSKeyedArchiver.archivedData(withRootObject: saveArticlesArray) as NSData
        UserDefaults.standard.set(encodedData, forKey: "newSave")
        UserDefaults.standard.synchronize()
    }
}