stumped
stumped

Reputation: 3293

How to fix this mutating error?

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];

Upvotes: 0

Views: 681

Answers (3)

Ric
Ric

Reputation: 8805

You need to create a NSMutableString like this:

[NSMutableString stringWithString: self.label.text];

Upvotes: 0

Mike D
Mike D

Reputation: 4946

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];

Upvotes: 1

Jack Lawrence
Jack Lawrence

Reputation: 10772

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];

Upvotes: 6

Related Questions