0

[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?

Hemang
  • 26,840
  • 19
  • 119
  • 186
  • 1
    try to allocate the str variable before using it. – Rama Rao Apr 12 '12 at 06:42
  • @RamaRao, I tried for it! Its not working. – Hemang Apr 12 '12 at 06:47
  • have u tried like this NSString *str = [[[NSString alloc] init] retain]; – Rama Rao Apr 12 '12 at 06:51
  • How are you declaring and setting `str` in your code? Where is the text in the string coming from (what other parts of your code) and is it mutable then? – David Rönnqvist Apr 12 '12 at 06:52
  • [str isKindOfClass:[NSMutableString class]], check wether this statement is returning true or not, i suspect this issue is due to immutable only. – rishi Apr 12 '12 at 06:54
  • @DavidRönnqvist, the string data of `VARCHAR` type coming from database, in format of `NSMutableDictionary`, I am accessing it like `str=[[NSMutableString stringWithFormat:@"%@",[dictionary valueForKey:@"title"]];` – Hemang Apr 12 '12 at 06:56
  • @RIP, As I written in my question when I checked for its class type, it converts to `NSCFString` – Hemang Apr 12 '12 at 06:58
  • @RamaRao, thank you! I again try for it! and it get solved:) – Hemang Apr 12 '12 at 07:06

1 Answers1

1

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.

keegan3d
  • 10,357
  • 9
  • 53
  • 77