如何在tableView中删除用户默认数据?

时间:2019-06-04 07:48:11

标签: ios swift uitableview nsuserdefaults

我使用用户默认设置添加了作业页面。 空值也添加到tableView和删除功能不起作用。

ButtonAction

 @IBAction func addHomeWork(_ sender: Any) {
        let newHomeWork = HomeWork(addtitle:addHomeworktxt.text!)
        HomeWork.saveHomeWork(homeWork: newHomeWork)
    }

viewWillAppear

   override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        if let arrayDetails = HomeWork.getHomeWork() {
            homeWorkArray = arrayDetails
        }
    }

EditingStyle

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == UITableViewCell.EditingStyle.delete {
        homeWorkArray.remove(at: indexPath.row)
        self.tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic)
        self.tableView.reloadData()
        HomeWork.getHomeWork()
    }
}

模型课程HomeWork

class HomeWork: Codable {
    var title:String
    init(addtitle:String) {
        self.title = addtitle}

    public static func getHomeWork() -> [HomeWork]? {
        var homeWorkArray:[HomeWork] = []
        if let homeWorkData = UserDefaults.standard.data(forKey: "homeworkData"){
            homeWorkArray = try! JSONDecoder().decode([HomeWork].self, from: homeWorkData)
        }
        return homeWorkArray
    }

在HomeWork模型类中保存HomeWork方法

    public static func saveHomeWork(homeWork:HomeWork){
        var retrivedHomeWorkArray:[HomeWork] = []

        if  let homeWorkData = UserDefaults.standard.data(forKey: "homeworkData"){
            retrivedHomeWorkArray = try! JSONDecoder().decode([HomeWork].self, from: homeWorkData)
        }


        if retrivedHomeWorkArray.count == 0 {
            var homeWorkArray = [HomeWork]()
            homeWorkArray.append(homeWork)
            let homeWorkDat = try! JSONEncoder().encode(homeWorkArray)
            UserDefaults.standard.set(homeWorkDat, forKey: "homeworkData")
        }else{

            retrivedHomeWorkArray.append(homeWork)
            let homeWorkDat = try! JSONEncoder().encode(retrivedHomeWorkArray)
            UserDefaults.standard.set(homeWorkDat, forKey: "homeworkData")  } }}

1 个答案:

答案 0 :(得分:1)

删除时,您不会更改已保存的数组

homeWorkArray.remove(at: indexPath.row)
self.tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic)
self.tableView.reloadData()
HomeWork.getHomeWork()

所以考虑添加一个函数来重新保存当前数组,例如

public static func reSave(homeWorks:[HomeWork]){ 
  let homeWorkDat = try! JSONEncoder().encode(homeWorks)
  UserDefaults.standard.set(homeWorkDat, forKey: "homeworkData") 
}

然后将上面的代码替换为

homeWorkArray.remove(at: indexPath.row)
self.tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic) 
HomeWork.reSave(homeWorks:homeWorkArray)