Getting “mutating method sent to immutable object” error

大兔子大兔子 提交于 2019-11-28 14:20:57

NSUserDefaults returns an immutable array. You need to make a mutable copy of it when you load it back up:

NSMutableArray *mutableArray = [[prefs objectForKey:@"container"] mutableCopy];
dataCenter.colourPalettesContainer = mutableArray;
[mutableArray release];

You might also have to do some manipulation inside of the array since you were storing NSMutableArrays within it.

Sherm Pendley

NSUserDefaults always returns immutable objects, even if what you stored was mutable. To work around this, you need to make a mutable copy. Since -mutableCopy returns an object that the caller owns, it needs to be (auto)released:

dataCenter.colourPalettesContainer = [[[prefs objectForKey:@"container"] mutableCopy] autorelease];

(Edit) I posted some -mutableDeepCopy NSArray & NSDictionary methods a while back, in response to another question. If your problem involves deeper nesting of collections, and you need them all to be mutable, this may help.

TO REMOVE AN OBJECT FROM PARTICULAR INDEX OF AN ARRAY. (Swift 3.0)

let fullArray : NSArray = Userdefaults().value(forKey: "YOUR_ARRAY_STRING") as! NSArray
var mutableArray : [AnyObject] = fullArray as [AnyObject]
mutableArray.remove(at: INDEX_TO_REMOVE) //Eg: mutableArray.remove(at: 0)
mutableArray.append(ARRAY_TO_APPEND)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!