Suleiman Suleiman - 1 year ago 71
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?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download