Jaa*_*nen 1 objective-c nsmutablestring ios declared-property
当我将一个字符串附加到NSMutableString使用时appendString:我得到以下错误:
Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: 'Attempt to mutate immutable object with appendString:'
Run Code Online (Sandbox Code Playgroud)
我的代码是:
self.partialWord = [NSMutableString stringWithCapacity:self.wordLength];
for (int i=0; i<wordLength; i++) {
[self.partialWord appendString:@"-"];
}
Run Code Online (Sandbox Code Playgroud)
在我的头文件中:
@property (copy, nonatomic, readwrite) NSMutableString *partialWord;
Run Code Online (Sandbox Code Playgroud)
我不明白为什么它说对象是不可变的,因为它是一个NSMutableString.为什么这[self.partialWord appendString:@"-"];部分不起作用?
问题是由于copy您的财产上的属性.为属性分配值时,它会创建一个副本.但副本是用copy而不是mutableCopy你实际上最终分配NSString给属性而不是NSMutableString.
摆脱copy属性或实现自己的自定义"setter"方法调用mutableCopy.
| 归档时间: |
|
| 查看次数: |
923 次 |
| 最近记录: |