首页 > 解决方案 > 当应用程序再次启动(Swift)时,如何加载存储在数组中的所有数据?

问题描述

我必须实现一个在应用程序启动时将存储的数据加载到购物清单数组中的函数,以及一个在按下按钮时存储我的列表当前内容的函数。我使用UserDefaults了类,它适用于第二个功能(按下按钮时),但不适用于第一个功能(应用程序启动时)。如果我重新启动应用程序并按下按钮,我会看到只存储了最后一个输入。如果我想存储数组中的所有数据,如何修复代码?

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var inputEntered: UITextField!

    // keyboard gives up the first responder status and goes away if return is pressed

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        inputEntered.resignFirstResponder()
        return true
    }

    var shoppingList: [String] = []

    @IBAction func buttonAddToList(_ sender: UIButton) {
        if let item = inputEntered.text, item.isEmpty == false { // need to make sure we have something here
            shoppingList.append(item) // store it in our data holder
        }
        inputEntered.text = nil // clean the textfield input

        print(shoppingList.last!) // print the last element to avoid duplicates on the console

        storeData()
    }

    // this function stores the current contents of my list when the button is pressed

    func storeData () {
        let defaults = UserDefaults.standard
        defaults.set(inputEntered.text, forKey: "Saved array")
        print(defaults)
    }

    // to call the function storeDate(), when the app restarts 

    override func viewDidLoad() {
        super.viewDidLoad()
        inputEntered.delegate = self
        // Do any additional setup after loading the view.
        storeData()
    }
}

标签: iosswift

解决方案


您可以将 getter 和 setter 添加到数组中,并将您的值保留为用户默认值。这样你就不需要在初始化数组时调用 storeData 和/或记住加载数据:

var shoppingList: [String] {
    get {
        UserDefaults.standard.stringArray(forKey: "shoppingList") ?? []
    }
    set {
        UserDefaults.standard.set(newValue, forKey: "shoppingList")
    }
}

推荐阅读