【问题标题】:Append an array and store in UserDefaults (Swift)附加一个数组并存储在 UserDefaults (Swift)
【发布时间】:2019-09-15 09:17:15
【问题描述】:

我的项目有一个带有 UITextField 的警报按钮,允许我输入一个字符串,然后将其附加到我已全局声明的数组中。此添加允许另一个 UITextField 在其下拉菜单中显示添加。但是,更改只会在应用程序保持打开状态时保存,并且在我尝试配置 U​​serDefaults 时不会保存。

我已经阅读了类似的 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)
    }

【问题讨论】:

    标签: arrays swift append nsuserdefaults


    【解决方案1】:

    我没有看到您实际写入默认值的位置。你应该有这样的一行: defaults.set(needIndicatorArray, forKey: "someKey")

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

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

    【讨论】:

    • 哈!我没有听说过“惰性”变量。我将尝试将它们静态添加到结构中。感谢您的指导。
    【解决方案2】:

    您需要保存到用户默认值,然后在需要时读回数组。

    我刚刚包含了下面的相关部分,当您应该保存到用户默认值时:

    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]()
    

    【讨论】:

    • 谢谢。这很有帮助。
    • 确实如此。像冠军一样工作。
    猜你喜欢
    • 2018-06-16
    • 2018-05-16
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多