我的项目有一个带有 UITextField 的警告按钮,允许我输入一个字符串,然后将其 append 到我已全局声明的数组。此添加允许另一个 UITextField 在其下拉菜单中显示添加。但是,更改只会在应用程序保持打开状态时保存,而不会在我尝试配置 UserDefaults 时保存。
我已经通读了看起来类似的 S.O.帖子,但我无法获得任何解决方案来解决我的问题。
(这是全局声明的。)
let defaults = UserDefaults.standard
(这也是全局的。)
var needIndicatorArray: [String] = ["SNAP", "EBT", "FVRX"]
(这是我用来追加上述数组的代码。此代码将追加数组,但在应用程序关闭并重新打开后不会保存添加。)
@IBAction func addNeedIndicator(_ sender: UIBarButtonItem) {
var textField = UITextField()
let alert = UIAlertController(title: "Add Need Indicator", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Add Item", style: .default) { (action) in
//This should append the global array once the user hits the add item on the UIAlert
self.needIndicatorArray.append(textField.text!)
}
alert.addTextField { (alertTextField) in
alertTextField.placeholder = "Create new item"
textField = alertTextField
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
最佳答案
您需要保存到用户默认值,然后在需要时读回数组。
我刚刚在下面包含了相关部分,您应该在什么时候保存到用户默认值:
let action = UIAlertAction(title: "Add Item", style: .default) { (action) in
// This should append the global array once the user hits the add item on the UIAlert
self.needIndicatorArray.append(textField.text!)
// You need to save to User Defaults
defaults.set(needIndicatorArray, forKey: "yourKey")
}
当你需要检索数组时,使用这个:
let array = defaults.object(forKey: "yourKey") as? [String] ?? [String]()
关于arrays - append 一个数组并存储在 UserDefaults 中(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55857770/