附加数组并存储在UserDefaults中(快速)

时间:2019-04-25 21:18:02

标签: arrays swift append nsuserdefaults

我的项目有一个带有UITextField的警报按钮,该按钮允许我输入一个String,然后将其附加到全局声明的数组中。此添加项允许另一个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)
    }

2 个答案:

答案 0 :(得分:0)

我看不到实际写入默认值的位置。您应该使用类似以下内容的一行: defaults.set(needIndicatorArray, forKey: "someKey")

但是,您也永远不会检查默认值。您需要使用以下方式加载它: needIndicatorArray = defaults.object(forKey: "someKey") as? [String] ?? ["SNAP", "EBT", "FVRX"]

顺便说一句,所有全局变量都是惰性的,您不应依赖它们。您最好在本地声明它们,或者在某些类或结构中将其声明为静态。顺便说一句,当我说“懒惰”时,我指的是一种变量,而不是评论您的编码风格。在某些情况下,惰性变量可能会丢失参考。

答案 1 :(得分:0)

您需要保存为“用户默认值”,然后在需要时读回阵列。

当您应保存为“用户默认值”时,我刚刚添加了以下相关部分:

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]()
相关问题