Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy vs strong properties [duplicate]

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?

like image 554
Krish Solanki Avatar asked Jul 04 '15 05:07

Krish Solanki


2 Answers

@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.

like image 166
Inder Kumar Rathore Avatar answered Oct 13 '22 14:10

Inder Kumar Rathore


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.

like image 4
Munahil Avatar answered Oct 13 '22 14:10

Munahil