gpt4 book ai didi

ios - 当应用程序再次启动(Swift)时,如何加载存储在数组中的所有数据?

转载 作者:行者123 更新时间:2023-12-01 16:12:19 26 4
gpt4 key购买 nike

我必须实现一个在应用程序启动时将存储的数据加载到购物 list 数组中的函数,以及一个在按下按钮时存储我的列表当前内容的函数。我用了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()
}
}

最佳答案

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

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

关于ios - 当应用程序再次启动(Swift)时,如何加载存储在数组中的所有数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61828216/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com