This is an array:
var myArray = [1]
It contains Int
values.
This is how I save an array in NSUserDefaults
. This code seems to be working fine:
NSUserDefaults.standardUserDefaults().setObject(myArray, forKey: "myArray")
This is how I load an array:
myArray = NSUserDefaults.standardUserDefaults().objectForKey("myArray")
The code above, though, retrieves an error. Why?
You want to assign an
AnyObject?
to an array ofInt
s, beacuseobjectForKey
returnsAnyObject?
, so you should cast it to array this way:If there are no values saved before, it could return nil, so you could check for it with:
Swift 4:
You should use
if let
to unwrap your optional value and also a conditional cast. By the way you should also usearrayForKey
as follow:Or use the nil coalescing operator
??
: