【问题标题】:How to add UserDefaults into a task list - Swift如何将 UserDefaults 添加到任务列表中 - Swift
【发布时间】:2020-04-22 09:48:26
【问题描述】:

我一直在尝试将 userDefaults 添加到我的代码中并尝试保存例如一个任务,以便下次打开应用程序时我仍然可以看到该任务。 没有退出了解 userDefaults 是如何工作的。也许有人可以帮助我?

taskList VC 文件:

@IBAction func doneButton_Tapped(_ sender: Any) { var newTask = taskList()

newTask.name = taskNameField.text!
newTask.dueDate = dueDatePicker.date

newTask.dateCreated = Date()

taskArr.append(newTask)


didCreateTask = true

self.navigationController?.popViewController(animated: true)

}

ma​​inVC 文件:

struct taskList {
    var name: String!
    var dateCreated: Date!
    var dueDate:Date!
}

private let listIdentifier = "listIdentifier"


var taskArr: [taskList] = []

let defauls = UserDefaults.standard

class ViewController: UIViewController {

    @IBOutlet var tableView:UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "Tasks List"

        tableView.delegate = self
        tableView.dataSource = self


    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        tableView.reloadData()

    }


    @IBAction func newTaskButton_Tapped(_ sender: Any){
        self.performSegue(withIdentifier: "newTaskSague", sender: nil)
    }



}




extension ViewController: UITableViewDelegate{
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
}


extension ViewController:UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {return taskArr.count}


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: listIdentifier, for: indexPath) as! listCell

        let row = indexPath.row
        let formatter = DateFormatter()

        cell.title?.text = taskArr[row].name

        formatter.dateStyle = .medium
        formatter.timeStyle = .short
        cell.subTitle?.text = "Due: \(formatter.string(from: taskArr[row].dueDate))"
        return cell
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete{
            taskArr.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)
        }
    }
}

【问题讨论】:

    标签: ios swift xcode uikit nsuserdefaults


    【解决方案1】:

    使用用户默认值,您几乎可以满足您的任何需求,但请注意,这是一个内部数据库,用于检查布尔值,整数最小数据,您需要作为额外逻辑而不是存储位置,我打算保存一个您的 Task 模型的大量条目,您应该考虑使用 CoreData。

    我的建议是在您的 UserDefaults 中保存一组任务(如果不是那么多),当您来自后台时,您需要检查您的 UserDefaults 是否为空,例如

    override func viewDidLoad() {
    super.viewDidLoad()
    
    let notificationCenter = NotificationCenter.default
    notificationCenter.addObserver(self, selector: #selector(appMovedToForeground), name: Notification.Name.UIApplicationWillEnterForeground, object: nil)
    }
    
    func appMovedToForeground() {
    
        print("come from background")
    }
    

    对于你需要使用归档器的对象数组,你需要在appMoveToForeground的方法中添加类似的东西:

    guard let dataTasks = UserDefaults.standard.object(forKey: "task") as? Data else { return nil }
    if let tasks = try NSKeyedUnarchiver.unarchivedObject(ofClasses: [Task.self], from: dataTasks){
                if tasks.isNotEmpty() {
    
                }
            }
        }
    

    【讨论】:

    • 请注意,您需要以与对象存档相同的方式保存任务,并记得添加 .synchonize() 方法
    • 我仍然不知道如何在我的代码中实现这一点。我不想保存大量数据,只是其中几个我不需要使用 coreData
    【解决方案2】:

    我仍然不知道如何在我的代码中实现这一点。我不想保存大量数据,只是其中几个我不需要使用 coreData

    【讨论】:

      猜你喜欢
      • 2022-06-24
      • 2016-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-24
      • 1970-01-01
      相关资源
      最近更新 更多