Attempt to mutate immutable object error

一世执手 提交于 2019-12-25 12:10:05

问题


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?


回答1:


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



回答2:


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;


来源:https://stackoverflow.com/questions/14541212/attempt-to-mutate-immutable-object-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!