I am fresher in iOS and I want to know that when we should use copy
in a property, e.g.
@property (nonatomic, retain) NSString* name;
vs
@property (nonatomic, copy) NSString* name;`
What is the difference between retain
and copy
, and when should I use one but not the other?
@property (nonatomic, copy) NSString* name;
is better, as NSString
is immutable and it's child class NSMutableString
is mutable.
As long as you are using NSString
through out, you won't see any difference. But when you start using NSMutableString
, things can get little dicey.
NSMutableString *department = [[NSMutableString alloc] initWithString:@"Maths"];
Person *p1 = [Person new];
p1.department = department;
//Here If I play with department then it's not going to affect p1 as the property was copy
//e.g.
[department appendString:@"You're in English dept."];
Had it been just retain it would have changed the department of the p1
.
So having copy is prefered in this case.
If NSString
is mutable
then it gets copied
. If its not, then it is retained
If you will use copy
, a new copy for the string will be created hence different memory address too. Whereas, if you will use retain
then it will be in the same memory address only the retain counter will change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With