【问题标题】:Error using NSMutableString property "Attempt to mutate immutable object with appendString:"使用 NSMutableString 属性时出错“尝试使用 appendString 改变不可变对象:”
【发布时间】:2014-06-01 17:27:08
【问题描述】:

当我使用appendString: 将字符串附加到NSMutableString 时,出现以下错误:

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

我的代码是:

self.partialWord = [NSMutableString stringWithCapacity:self.wordLength];
for (int i=0; i<wordLength; i++) {
    [self.partialWord appendString:@"-"];
}

在我的头文件中:

@property (copy, nonatomic, readwrite) NSMutableString *partialWord;

我不明白为什么它说对象是不可变的,因为它是NSMutableString。为什么[self.partialWord appendString:@"-"]; 部分不起作用?

【问题讨论】:

    标签: ios objective-c nsmutablestring declared-property


    【解决方案1】:

    问题是由于您的资源的copy 属性造成的。当您为属性分配值时,它会创建一个副本。但是副本是使用copy 而不是mutableCopy 制作的,因此您实际上最终将NSString 分配给属性而不是NSMutableString

    摆脱属性上的copy 或实现您自己的调用mutableCopy 的自定义“setter”方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-23
      • 1970-01-01
      相关资源
      最近更新 更多