如何解决这个变异错误?

时间:2013-03-18 01:15:32

标签: ios objective-c nsmutablestring

我收到了这个错误:

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

3 个答案:

答案 0 :(得分:6)

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

例如:

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

需要:

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

答案 1 :(得分:1)

您的NSMutableString实际上是NSString的实例。这是运行时细节,但至少应该对这些行发出警告。改为:

NSMutableString *string = [self.label.text mutableCopy];

答案 2 :(得分:0)

您需要像这样创建NSMutableString

[NSMutableString stringWithString: self.label.text];