为什么这个字符串是不可变的?

时间:2013-08-10 23:58:55

标签: objective-c cocoa

为什么代码会给出错误 - 尝试使用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

2 个答案:

答案 0 :(得分:4)

因为[response stringWithRange:range]返回一个不可变的NSString *,并且强制转换不会使它变得可变。

您想要value = [[response stringWithRange:range] mutableCopy];

请注意,如果您不使用ARC,则需要记住发布mutableCopy。虽然[response stringWithRange:range]的返回值是自动释放的,但mutableCopy不是。

答案 1 :(得分:2)

我认为你不能像这样把字符串变成可变的。

你需要这样做

ms = [[NSMutableString alloc] init];
[ms setString:immutableString];

糟糕的是,子类的工作方式错了,你应该能够更简单地做到这一点。

ms = [NSMutableString stringWithString: immutableString];
相关问题