Attempting to use the copied NSMutableString property throws an exception

I started a small Xcode project to find out if there should be an NSMutableString copy or retain property. I declared my property as a copy attribute:

 @property (nonatomic,copy) NSMutableString *stringA; 

Then initialized it as self.stringA = [NSMutableString new];

finally tried to set the string [stringA setString:@"A"]; .

However, the program gives

"The application terminated due to an unmanaged exception" NSInvalidArgumentException ", reason: 'Attempting to mutate an immutable object using setString:'"

Is it because the resulting string is an NSString ? Does this mean that I should declare my NSMutableString properties using retain and NSString attributes with copy ?

+4
source share
2 answers

You're right, the copy method NSMutableString returns an immutable NSString . This convention is in Cocoa, it also applies to NSMutableArray , NSMutableDictionary , etc.

So, if you want your property to remain volatile, you must declare it as retain . If you need a copy of semantics, but still want the result to be changed, you would need to implement your own setter for the property (and use mutableCopy for copying).

The reason you usually see copy for string properties is because it is often desirable to have a guarantee that the string is immutable, regardless of which string is assigned to the property. Otherwise, you may accidentally change the same line in another place, which can be difficult to debug. Immutable objects can also be thread safe.

+10
source

The first question I would ask is initializing stringA. If you install it from a simple string, that is probably why you get this. Copying and saving is actually done differently, and you should know why you are using one or the other.

The copy actually creates a copy of the memory, so that any changes you make to this property do not affect the source file from which it was installed, from which only the increase in memory in memory is saved, so you guarantee that it will not be released until as long as you made a link to it.

-1
source

All Articles