我想把一个Swift样式字符串数组保存到NSUserDefaults,但是在代码中的“if”语句表示returnValue总是nil。
后来在代码中我想使用“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() } }
以下代码可以帮助您解决问题:
原文链接:https://www.f2er.com/swift/321017.htmlimport 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 = [],你会有一个问题,因为食物不会返回[“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","spaghetti"] food = [] print(food) // prints: ["muesli","banana"] NSUserDefaults.standardUserDefaults().setObject(nil,"banana"] } }