ERROR for attempting mutating immutable object

半城伤御伤魂 提交于 2019-12-12 02:28:58

问题


What is this error? I am using mutable type but still it is not working!

ERROR IS :

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'mutate immutable object with deleteCharactersInRange:'

NSMutableString *line= [NSMutableString stringWithString:@"here is the string"];
[line deleteCharactersInRange: NSMakeRange(1,9 )];

回答1:


My new answer:

With your new code, I added one extra line at the end:

NSMutableString *line= [NSMutableString stringWithString:@"here is the string"];
[line deleteCharactersInRange: NSMakeRange(1,9 )];
NSLog( @"line is %@", line );

And the console output was:

2011-11-25 06:08:13.248 TestingCommandLine[13324:903] line is he string

No exception thrown. Looks like it's working for me!

My original answer (for your original question):

You can't delete characters from a line that has nothing in it (hence the exception).

Do you have any additional code between those two lines of source there? If not, you have a valid NSMutableString... with nothing in it. And you can't delete anything from a mutable string that has nothing in it.




回答2:


If your code looks exactly as you've quoted here, then the issue is that you're trying to delete something from an empty string. But since there's nothing that can be delete it's an error.




回答3:


The exception name is clear: "Invalid Argument". What you did was to create an empty mutable string and then trying to delete characters in a range 1..9 well beyond the limits. This function is not tolerant for out of range: it raises an exception. Why you write the comment "line has value!"? are you generating it in between the two lines of code that you posted?



来源:https://stackoverflow.com/questions/8267956/error-for-attempting-mutating-immutable-object

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