我收到了这个错误:
*** 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];
答案 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];