Suleiman Suleiman - 5 months ago 15
iOS Question

Can't modify array stored in NSUserDefaults

In a class

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

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

Then, in another class
, I try

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

func confirmPressed() {

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?


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