Store [String] in NSUserDefaults

前端 未结 5 1106
南方客
南方客 2020-11-27 17:35

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 (

5条回答
  •  伪装坚强ぢ
    2020-11-27 18:19

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

提交回复
热议问题