Getting an error when using replaceOccuranceOfString function

614 views Asked by At

[str replaceOccurrencesOfString: withString: options: range:

[str replaceOccurrencesOfString:@"'" withString:@"!~" options:0 range:NSMakeRange(0,str.length)]

I am using this function to replace ' symbol in my NSMutableString with !~ symbol so that I can store that string into database. Its working fine when I stored it into database, but at the time of retrieving and convert it back using same function it showing me error like.

Error *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to mutate immutable object with replaceOccurrencesOfString:withString:options:range:'

Here, str is of NSMutableString type. I checked for its type [str class] its converts to NSCFString don't know why its changing? I also try to convert it to NSMutableString, but its not converting. I am trying for it for so many times in some other ways, but its working fine with all other places, only in my one view controller, it showing me this.

Any guesses where's I am doing wrong?

1

There are 1 answers

0
keegan3d On BEST ANSWER

You don't show how you are converting the immutable from the data base to a mutable string. Just doing NSMutableString *mstr = str; isn't enough, you'd need to use NSMutableString *mstr = [NSMutableString stringWithString:str];.

Because the returned string is immutable you might want to consider using [NSString stringByReplacingOccurrencesOfString:withString:] instead of working with mutable strings.