I want to save a Swift Style String Array into NSUserDefaults, but acutally the \"if\" statement in the code says that returnValue is always nil.
Later in the code (
As stated in the documentation:
For NSArray and NSDictionary objects, their contents must be property list objects.
This means you need to convert your String objects to NSString when saving, something like this should work:
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) {
// Each item in newValue is now a NSString
let val = newValue as [NSString]
NSUserDefaults.standardUserDefaults().setObject(val, forKey: "food")
NSUserDefaults.standardUserDefaults().synchronize()
}
}