Pregunta

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];
¿Fue útil?

Solución

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

Otros consejos

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

You need to create a NSMutableString like this:

[NSMutableString stringWithString: self.label.text];
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top