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?
The problem is due to the
copyattribute on your property. When you assign a value to the property, it creates a copy. But the copy is made withcopyand notmutableCopyso you actually end up assigning anNSStringto the property and not anNSMutableString.Get rid of
copyon the property or implement your own custom "setter" method that callsmutableCopy.