0

My code crashes at this line:

[(NSMutableString *)string replaceCharactersInRange:range withString:@""];

with the error attempt to mutate immutable object.

How is this happening and how do i fix it?

Alex
  • 451
  • 5
  • 13
  • 5
    Now you're going back to reading a tutorial on typecasting in C. **Now.** –  Jan 26 '13 at 20:25

2 Answers2

7

The string isn't mutable, casting is not magic, it wouldn't turn it into a mutable string. You should do it on a mutable copy:

NSMutableString* mutableString= [string mutableCopy];
[mutableString replaceCharactersInRange:range withString:@""];
Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187
3

You are typecasting an immutable string and then mutating it, actually this is not happening.

You need to create a new NSMutableString and then use replaceCharactersInRange...

NSMutableString *mutableString=[NSMutableString stringWithString:string];
[mutableString replaceCharactersInRange:range withString:@""];

If you want the result in same object set it to string.

string=mutableString;
Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140