ios - 当应用程序再次启动(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()
}
}
解决方案
您可以将 getter 和 setter 添加到数组中,并将您的值保留为用户默认值。这样你就不需要在初始化数组时调用 storeData 和/或记住加载数据:
var shoppingList: [String] {
get {
UserDefaults.standard.stringArray(forKey: "shoppingList") ?? []
}
set {
UserDefaults.standard.set(newValue, forKey: "shoppingList")
}
}
推荐阅读
- mysql - 仅获取用户在练习 _id 上的最后一次 trynumber 报告
- python - dict_student[id] = [item[1]] 和 dict_student[id].append(item[1]) 的区别?
- java - 将mysql服务器连接到android应用程序(java)错误
- azure - 最佳实践 - 本地 Node.js (*.env) 到远程 Azure 应用服务(配置设置)
- r - VAR 模型:如何获得自举的 95% 预测区间?
- google-apps-script - Google Sheets Script TimeStamp 不会返回 AM/PM 或 24 小时时间
- html - 是否可以将登录凭据发送到服务器以在正文中使用 content-type: application/json 进行身份验证和授权?
- excel-formula - Excel 上的 SUMIFS 公式
- pycharm - 带有填充的 __init__ 文件的 Pycharm 和未解决的引用
- python - 如何在不使用循环的情况下将 FamousAuthors 列表汇总到另一个字典?