What is the difference between copy
and retain
for NSString
?
- (void)setString:(NSString*)newString
{
string = [newString copy];
}
See Question&Answers more detail:osWhat is the difference between copy
and retain
for NSString
?
- (void)setString:(NSString*)newString
{
string = [newString copy];
}
See Question&Answers more detail:osIn a general setting, retaining an object will increase its retain count by one. This will help keep the object in memory and prevent it from being blown away. What this means is that if you only hold a retained version of it, you share that copy with whomever passed it to you.
Copying an object, however you do it, should create another object with duplicate values. Think of this as a clone. You do NOT share the clone with whomever passed it to you.
When dealing with NSString
s in particular, you may not be able to assume that whoever is giving you an NSString
is truly giving you an NSString
. Someone could be handing you a subclass (NSMutableString
, in this case) which means that they could potentially modify the values under the covers. If your application depends on the value passed in, and someone changes it on you, you can run into trouble.