Suleiman Suleiman - 4 months ago 12
iOS Question

Can't modify array stored in NSUserDefaults

In a class

FirstViewController
, I add an array with key
rentedItems
to the NSUserDefaults in the following lines:

let itemArray = [Item]()
let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
prefs.setObject(itemArray, forKey: "rentedItems")


Then, in another class
SecondViewController
, I try

var item: Item?
var prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()

func confirmPressed() {
prefs.arrayForKey("rentedItems")?.append(item)
}


This then gives the following error:
Cannot use mutating member on immutable value: function call returns immutable value
. I saw a solution in SO here that gave me an idea of the problem, but NSUserDefaults being a default iOS class, I can't use the same solution as there. Any ideas?

Answer

You can't directly modify an array from defaults. Instead make a copy, and modify that. You can save that array to defaults afterwards. Simply try like this:

var array = prefs.arrayForKey("rentedItems")?.mutableCopy
array.append(item)