Alex
Alex

Reputation: 449

Attempt to mutate immutable object error

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?

Upvotes: 0

Views: 2286

Answers (2)

Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 22006

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:@""];

Upvotes: 7

Anoop Vaidya
Anoop Vaidya

Reputation: 46563

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;

Upvotes: 3

Related Questions