views:

109

answers:

1

Hi,

I've seen a few posts on here about the issue of using retain or copy for strings. I still can't quite get my head around the difference or the importance.

In my case at the moment I have a class with a whole load of nsstrings to hold strings.

I want this class to only be instantiated once and I want its nsstring variables to change depending on the index clicked in a table view.

Would I be correct in saying that if I chose to use retain that my nsstrings would be overwritten each time I set their value on my tableview click and that if I chose copy I would somehow have 2 instances of each string....?

I'm sorry ..... I totally don't get it

+1  A: 

This is a question about copying mutable objects vs. immutable ones. Since NSString objects are immutable (you cannot change their contents), they implement -copy like this:

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

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

If your strings are not NSMutableStrings, it does not matter whether you retain or copy them. However, choosing the right method is important if you later refactor your code to use NSMutableStrings. A common logic should answer the following question for you: if I get an object whose contents may change outside, which value do I need? More often than not you will want to make a copy.

Costique
Thank you for the clarification! I didn't know that `[NSString copy]` would just retain.
MrMage