gpt4 book ai didi

ios - 使用 NSMutableString 属性时出错 "Attempt to mutate immutable object with appendString:"

转载 作者:行者123 更新时间:2023-12-01 17:52:53 29 4
gpt4 key购买 nike

当我将字符串附加到 NSMutableString使用 appendString:我收到以下错误:

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:@"-"];部分不起作用?

最佳答案

问题是由于 copy您的属性(property)上的属性。当您为属性分配值时,它会创建一个副本。但是副本是用 copy 制作的而不是 mutableCopy所以你实际上最终分配了 NSString到属性(property)而不是NSMutableString .

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

关于ios - 使用 NSMutableString 属性时出错 "Attempt to mutate immutable object with appendString:",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23982510/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com