根据用户默认值在Tableview控制器中显示对象数组

问题描述

我一直无法以用户默认值存储数组对象中的数据。为了将对象存储为用户默认值,我将对象编码为json,当我需要读取它时,我对该对象进行解码。我的应用程序中的表视图控制器成功显示了我的应用程序中的整个数组,但是,当我重新启动该应用程序以确保它将再次从用户默认值读取时,表视图控制器中仅显示该数组的最新添加内容。这很可能是由于encodeArray.removeAll()。当我删除“ removeAll()”函数调用时,每个对象的重复项都会在表视图中显示,仅当我重新启动该应用程序时才能正确显示。任何帮助将不胜感激!

这是包含tableview控制器的视图控制器。当单独的VC添加到对象数组时,它将发送一个后置通知以返回,加载该数组并重新加载数据。

    @IBOutlet weak var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.delegate = self
        tableView.dataSource = self
        
        NotificationCenter.default.addObserver(self,selector: #selector(returnToVC(_:)),name: Notification.Name(rawValue: "returnToVC"),object: nil)

        goalLoadService.instance.loadGoals()
        tableView.reloadData()
        self.revealViewController().rearViewRevealWidth = self.view.frame.size.width - 80
    }
    
    @objc func returnToVC(_ notification: Notification) {
        goalLoadService.instance.loadGoals()
        tableView.reloadData()
    }
   
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
        return goalLoadService.instance.goals.count
    }
    
    func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "goalCell",for: indexPath) as? GoalCell {
            let goal = goalLoadService.instance.goals[indexPath.row]
            cell.configureCell(goal: goal)
            return cell
        } else {
            return UITableViewCell()
        }
    }

这是当用户添加到数组时在第二个VC中调用的IBAction。然后将该对象编码为JSON并存储在用户默认设置中。在撤消之前,会发出发布通知。

@IBAction func onBeginTapped(_ sender: Any) {
        if let duration: Int = Int(goalDurationTxt.text!){
            let goalObject = GoalDataModel(goalTitle: goalNameTxt.text!,goalDuration: duration)
            goalLoadService.instance.encodeJSON(goalObject: goalObject)
            NotificationCenter.default.post(name: Notification.Name(rawValue: "returnToVC"),object: nil)
            dismiss(animated: true,completion: nil)
        }
    }

这是根据用户默认值对对象进行编码和解码的服务。从用户默认值读取时,在loadGoals()中调用'decodeJSON',而在写入用户默认值时调用'encodeJSON'。作为参考,GoalDataModel是具有字符串标题属性和整数(持续时间)属性的可编码结构。

此外,在一个单独的文件中,为用户默认值定义了一个常量。

let DEFAULTS = UserDefaults.standard
class goalLoadService {
    
    static let instance = goalLoadService()
    
    var encodeArray: [Data] = DEFAULTS.array(forKey: "goalArray") as? [Data] ?? []
    
    
    var goals: [GoalDataModel] = [GoalDataModel]()
    
    
    func loadGoals(){
        guard let array = DEFAULTS.array(forKey: "goalArray") else {
            return
        }
        
        decodeJSON(array: array as! [Data])
    }
    
    func encodeJSON(goalObject: GoalDataModel) {
        
        let encoder = JSONEncoder()
        
        guard let encoded = try? encoder.encode(goalObject) else {
            return
        }
        encodeArray.removeAll()
        encodeArray.append(encoded)
        DEFAULTS.removeObject(forKey: "goalArray") 
        DEFAULTS.set(encodeArray,forKey: "goalArray")
    }
    
    
    func decodeJSON(array: [Data]){
        for goalData in array {
            let decoder = JSONDecoder()
            if let loadedGoal = try? decoder.decode(GoalDataModel.self,from: goalData) {
                goals.append(loadedGoal)
            }
        }
    }
}

解决方法

decodeJSON函数中,您要将解码后的值添加到现有的goals数组中,这就是重复的原因。因此,请在loadGoals函数中重置目标数组,并且在添加新项目时不必使用encodeArray.removeAll()

func loadGoals(){
    guard let array = DEFAULTS.array(forKey: "goalArray") else {
        return
    }
    goals = []
    decodeJSON(array: array as! [Data])
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...