NSString keep a copy of the question

I saw several posts here about the issue of using save or copy for strings. I still can’t make out the difference or importance.

In my case, at the moment I have a class with all the loading of nsstrings for storing strings.

I want this class to have only one instance, and I want its nsstring variables to change depending on the index clicked in the form of a table.

I would be right in saying that if I decided to use, save that my nsstrings will be overwritten every time I set their value in my tableview click and that if I select a copy I would have something like 2 instance of each row ....

Sorry, I do not completely understand.

+4
source share
1 answer

This is a matter of copying mutable objects compared to immutable ones. Since NSString objects are immutable (you cannot change their contents), they implement -copy as follows:

- (id) copyWithZone: (NSZone *) zone { return [self retain]; } 

If you think about it, there is no reason to duplicate an immutable object, because it is a waste of memory. On the other hand, NSMutableString objects can see a change in their contents during their lifetime, so if you request a copy of NSMutableString you will get a real copy, another object.

If your strings are not NSMutableStrings, it doesn't matter if you save or copy them. However, choosing the right method is important if you later reorganize your code to use NSMutableStrings. General logic should answer the following question: if I get an object whose contents can change outside, what value do I need? Most often you will want to make a copy.

+6
source

Source: https://habr.com/ru/post/1301803/


All Articles