0

I'm getting this error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to mutate immutable object with replaceCharactersInRange:withString:'

But I can't figure out what immutable object I'm mutating.

        NSRange subRange = [self.label.text rangeOfString: @"="];
        int numA = 5;
        int numB = 3;

        NSMutableString *mixed = [NSString stringWithFormat: @"%i %i", numA, numB];

        NSMutableString *string = [NSString stringWithString: self.label.text];

        subRange = [string rangeOfString: @"="];

        if (subRange.location != NSNotFound)
            [string replaceCharactersInRange:subRange withString:mixed];
stumped
  • 3,235
  • 7
  • 43
  • 76
  • 1
    Your string variable isn't mutable and you ate attempting to mutate it. – Jeremy Mar 18 '13 at 01:19
  • duplicate of http://stackoverflow.com/questions/14541212/attempt-to-mutate-immutable-object-error http://stackoverflow.com/questions/8267956/error-for-attempting-mutating-immutable-object – Sebastian Mar 18 '13 at 01:24

3 Answers3

6

Your NSMutableString creation calls aren't balanced properly. You're promising the compiler that you're creating a NSMutableString but you ask an NSString to create an instance.

For example:

NSMutableString *mixed = [NSString stringWithFormat: @"%i %i", numA, numB];

needs to be:

NSMutableString *mixed = [NSMutableString stringWithFormat: @"%i %i", numA, numB];

Jack Lawrence
  • 10,664
  • 1
  • 47
  • 61
1

Your NSMutableStrings are actually instances of NSString. This is runtime detail, though there should at least be a warning for those lines. Change to:

NSMutableString *string = [self.label.text mutableCopy];
Mike D
  • 4,938
  • 6
  • 43
  • 99
0

You need to create a NSMutableString like this:

[NSMutableString stringWithString: self.label.text];
Navnath Godse
  • 2,233
  • 2
  • 23
  • 32
Ric
  • 8,615
  • 3
  • 17
  • 21