Search code examples
objective-ccocoa

Why is this string immutable?


Why does the code give the error - Attempt to mutate immutable object with 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];
}

Value is being created as a _NSCFString.


Solution

  • Because [response stringWithRange:range] returns an immutable NSString *, and casting doesn't make it become mutable.

    You want value = [[response stringWithRange:range] mutableCopy];.

    Note that if you're not using ARC, you need to remember to release the mutableCopy. Although the return value of [response stringWithRange:range] is autoreleased, the mutableCopy is not.