I need create an array to add objects with this format like a dictionary in Swift : ["key1": "value1", "key2": "value2"]
When I try to save it with NSUserDefaults
all is correct, but when read NSUserDefaults
with the key this crashes. What type of data does my var obj need?
let def = NSUserDefaults.standardUserDefaults()
var key = "keySave"
var element: AnyObject!
var array1: [AnyObject!] = []
array1.append(["key1": "val1", "key2": "val2"])
array1.append(["key1": "val1", "key2": "val2"])
//save
var savestring : [AnyObject!]
savestring = array1
var defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(savestring, forKey: key)
defaults.synchronize()
//read
var obj: [AnyObject!] = []
if(obj != nil){
print("size: ")
print(obj.count) //vary long value confused..
element = obj[0] //crash
print(element.objectForKey("key1"))
}
The question reads "array of array" but I think most people probably come here just wanting to know how to save an array to UserDefaults
. For those people I will add a few common examples.
Save array
let array = ["horse", "cow", "camel", "sheep", "goat"]
let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedStringArray")
Retrieve array
let defaults = UserDefaults.standard
let myarray = defaults.stringArray(forKey: "SavedStringArray") ?? [String]()
Save array
let array = [15, 33, 36, 723, 77, 4]
let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedIntArray")
Retrieve array
let defaults = UserDefaults.standard
let array = defaults.array(forKey: "SavedIntArray") as? [Int] ?? [Int]()
Save array
let array = [true, true, false, true, false]
let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedBoolArray")
Retrieve array
let defaults = UserDefaults.standard
let array = defaults.array(forKey: "SavedBoolArray") as? [Bool] ?? [Bool]()
Save array
let array = [Date(), Date(), Date(), Date()]
let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedDateArray")
Retrieve array
let defaults = UserDefaults.standard
let array = defaults.array(forKey: "SavedDateArray") as? [Date] ?? [Date]()
Custom objects (and consequently arrays of objects) take a little more work to save to UserDefaults
. See the following links for how to do it.
??
) allows you to return the saved array or an empty array without crashing. It means that if the object returns nil, then the value following the ??
operator will be used instead.Int
, Bool
, and Date
. I also tested it with Double
. As far as I know, anything that you can save in a property list will work like this.