一尘不染

将[String]存储在NSUserDefaults中

swift

我想将Swift样式字符串数组保存到NSUserDefaults中,但是代码中的“ if”语句通常说returnValue始终为nil。

在稍后的代码中(iOS 8),我想使用“ food + = [” spaghetti“]添加新条目。

var food : [String] {
    get {
        var returnValue : [String]? = NSUserDefaults.standardUserDefaults().objectForKey("food") as? [String]
        if returnValue == nil      //Check for first run of app
        {
            returnValue = ["muesli", "banana"]; //Default value
        }
        return returnValue!
    }
    set (newValue) {
        NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "food")
        NSUserDefaults.standardUserDefaults().synchronize()
    }
}

阅读 271

收藏
2020-07-07

共1个答案

一尘不染

以下代码应帮助您解决问题:

import UIKit

class ViewController: UIViewController {

    var food: [String] {
        get {
            if let returnValue = NSUserDefaults.standardUserDefaults().objectForKey("food") as? [String] {
                return returnValue
            } else {
                return ["muesli", "banana"] //Default value
            }
        }
        set {
            NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "food")
            NSUserDefaults.standardUserDefaults().synchronize()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        print(food) // prints: ["muesli", "banana"] (at first launch)

        food = ["cake"]
        print(food) // prints: ["cake"]

        food += ["spaghetti"]
        print(food) // prints: ["cake", "spaghetti"]

        food = []
        print(food) // prints: []

        NSUserDefaults.standardUserDefaults().setObject(nil, forKey: "food")
        print(food) // prints: ["muesli", "banana"]
    }

}

但是,使用前面的代码,如果您设置food = [],则会遇到问题,因为food不会返回["muesli", "banana"]。为了避免这种情况,您可能更喜欢以下代码:

import UIKit

class ViewController: UIViewController {

    var food: [String] {
        get {
            if let returnValue = NSUserDefaults.standardUserDefaults().objectForKey("food") as? [String] {
                return returnValue == [] ? ["muesli", "banana"] : returnValue
            } else {
                return ["muesli", "banana"] //Default value
            }
        }
        set {
            NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "food")
            NSUserDefaults.standardUserDefaults().synchronize()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        print(food) // prints: ["muesli", "banana"] (at first launch)

        food = ["cake"]
        print(food) // prints: ["cake"]

        food += ["spaghetti"]
        print(food) // prints: ["cake", "spaghetti"]

        food = []
        print(food) // prints: ["muesli", "banana"]

        NSUserDefaults.standardUserDefaults().setObject(nil, forKey: "food")
        print(food) // prints: ["muesli", "banana"]
    }

}
2020-07-07