0

我有一个需要更改其属性之一的业务对象。我尝试获取该属性的字符串表示形式,然后对其进行修改,就像我在下面的代码中尝试一样

  NSMutableString *mutatingString = [ [ NSMutableString alloc ] init ] ;
  mutatingString = ( NSMutableString * ) [ businessOject valueForKey:@"basicproperty" ] ;
  [ mutatingString appendString:@"Modified" ];

但是,当我在 appendString 的第三行加热时,我得到以下异常:

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

我的代码有什么问题?

4

1 回答 1

1

您不应将 [ businessOject valueForKey:@"basicproperty" ] 的结果从 NSString* 转换为 NSMutableString*。

NSString* str  =   [businessOject valueForKey:@"basicproperty" ];
NSMutableString *mutatingString = [[NSMutableString alloc ] initWithString:str  ] ;
[mutatingString appendString:@"Modified" ];
[businessOject setValue:mutatingString forKey:@"basicproperty" ] 
于 2012-10-22T15:34:19.883 回答