2013-03-18 169 views
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]; 
+1

您的字符串變量不可變,並且您嘗試對其進行變異。 – Jeremy 2013-03-18 01:19:07

+0

http://stackoverflow.com/questions/14541212/attempt-to-mutate-immutable-object-error http://stackoverflow.com/questions/8267956/error-for-attempting-mutating-immutable-object – Sebastian 2013-03-18 01:24:09

回答

6

NSMutableString創建呼叫不正確的平衡。您承諾編譯器創建NSMutableString,但您要求NSString創建一個實例。

例如:

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

需求是:

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

0

你需要創建一個NSMutableString這樣的:

[NSMutableString stringWithString: self.label.text]; 
1

NSMutableString s爲實際的NSString實例。這是運行時細節,儘管至少應該爲這些行提供警告。更改爲:

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