Search code examples
iosobjective-cnsmutablestringdeclared-property

Error using NSMutableString property "Attempt to mutate immutable object with appendString:"


When I to append a string to an NSMutableString using appendString: I get the following error:

Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: 'Attempt to mutate immutable object with appendString:'

My code is:

self.partialWord = [NSMutableString stringWithCapacity:self.wordLength];
for (int i=0; i<wordLength; i++) {
    [self.partialWord appendString:@"-"];
}

And in my header file:

@property (copy, nonatomic, readwrite) NSMutableString *partialWord;

I don't understand why it says the object is immutable as it's an NSMutableString. Why does the [self.partialWord appendString:@"-"]; part not work?


Solution

  • The problem is due to the copy attribute on your property. When you assign a value to the property, it creates a copy. But the copy is made with copy and not mutableCopy so you actually end up assigning an NSString to the property and not an NSMutableString.

    Get rid of copy on the property or implement your own custom "setter" method that calls mutableCopy.