Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

iphone - Getting "mutating method sent to immutable object" error

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

and then:

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?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...