为什么代码会给出错误-尝试使用appendFormat:对不可变对象进行突变?
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
for (NSTextTestingResult *match in matches) {
<omitted>
NSMutableString *value;
value = (NSMutableString *)[response stringWithRange:range];
if ([dict objectForKey:@"traveler"])
[dict objectForKey:@"traveler"] appendFormat:@"%@", value]; // Errors here
[dict setObject:value forKey:key];
}
值被创建为_NSCFString
。
因为[response stringWithRange:range]
返回一个不可变的NSString *
,并且强制转换不会使它变得可变。
你要value = [[response stringWithRange:range] mutableCopy];
。
请注意,如果您不使用ARC,则需要记住释放mutableCopy
。尽管的返回值[response stringWithRange:range]
是自动释放的,但mutableCopy
不是。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句