0

我收到此错误:

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

但我无法弄清楚我正在变异的不可变对象。

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

3 回答 3

6

您的NSMutableString创建调用未正确平衡。您向编译器承诺您正在创建一个NSMutableString,但您要求一个NSString创建一个实例。

例如:

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

需要是:

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

于 2013-03-18T01:19:19.453 回答
1

NSMutableString的 s 实际上是NSString. 这是运行时详细信息,但至少应该对这些行发出警告。改成:

NSMutableString *string = [self.label.text mutableCopy];
于 2013-03-18T01:19:52.670 回答
0

您需要创建一个NSMutableString这样的:

[NSMutableString stringWithString: self.label.text];
于 2013-03-18T01:19:14.573 回答