error : 'Attempt to mutate immutable object wi

2019-05-10 08:58发布

问题:

I am getting an error 'Attempt to mutate immutable object with appendString:'

and my code is

NSMutableString *resultString= [[NSMutableString alloc]init];


for (NSMutableString *s in self.ArrayValue)
{
    [resultString appendString:s];
    NSLog(resultString);

}  

ArrayValue is NSMutableArray.
I am not able to understand where is the problem

thank you in advance

回答1:

As posted, the code you have will not give you the error you describe. Probably, somewhere between allocating resultString and the for loop, you are overwriting it with a normal NSSring.



回答2:

Just do have like this:

It works for me...

    NSMutableString *resultString= [[NSMutableString alloc]init];
NSMutableArray *ArrayValue=[[NSMutableArray alloc]init];
[ArrayValue addObject:@"One"];
[ArrayValue addObject:@"Two"];
[ArrayValue addObject:@"Three"];

for (NSMutableString *s in ArrayValue)
{
    [resultString appendString:s];
    NSLog(@"%@",resultString);------->You should use %@ to print the string otherwise will show your warning.

}  

O/P on Console:

2011-03-08 19:13:02.243 iPadMables[4557:207] One

2011-03-08 19:13:06.224 iPadMables[4557:207] OneTwo

2011-03-08 19:13:09.388 iPadMables[4557:207] OneTwoThree



回答3:

    ArrayValue = [NSMutableArray arrayWithObjects:@"b",@"o",@"n",nil];
NSMutableString *resultString= [[NSMutableString alloc]init];

for (NSMutableString *s in self.ArrayValue)
{
    [resultString appendString:s];
    NSLog(resultString);

}  

works for me..