获取“发送到不可变对象的变异方法”错误 [英] Getting "mutating method sent to immutable object" error

查看:122
本文介绍了获取“发送到不可变对象的变异方法”错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚造成这种情况的原因。基本上,一些不同的任务在我的应用程序中相互冲突。当我按下按钮时,它运行此代码就好了:

I can't figure out what is causing this. Basically, a few different 'tasks' are colliding with each other in my app. When i press a button, it runs this code just fine:

PalAppDelegate *dataCenter = (PalAppDelegate *)[[UIApplication sharedApplication] delegate];




[dataCenter.colourPalettesContainer addObject:[NSNumber numberWithInt:5]];

它可以随心所欲地执行此操作。但是,当我执行另一项任务时(还有一些会导致这种情况发生),这涉及到以下代码:

It can do this as many times as i like. But when i perform another task (and theres a few which cause this to happen), which involves this code for example:

PalAppDelegate *dataCenter = (PalAppDelegate *)[[UIApplication sharedApplication] delegate];

[dataCenter.colourPalettesContainer removeObjectAtIndex:touchDownID];

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:dataCenter.colourPalettesContainer forKey:@"container"];
[prefs synchronize];

然后:

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

当我在此之后再次运行第一个代码时,会导致崩溃,并发送变异方法不可变对象错误。我怎么能阻止这个?

When i run the first code again after this, it causes a crash with the "mutating method sent to immutable object" error. How can i stop this?

编辑:所以我从下面的一些答案中找到了问题。有没有人有他们建议的不同方法?

So i've found out the problem from some answers below. Does anybody have a different method of doing this which they'd suggest?

推荐答案

NSUserDefaults返回一个不可变数组。你需要在加载它时制作一个可变副本:

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];

您可能还需要在数组内部进行一些操作,因为您在其中存储了NSMutableArrays。

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

这篇关于获取“发送到不可变对象的变异方法”错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆