10

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?

Krish Solanki
  • 249
  • 4
  • 11
  • Generally, I use retain for objects like NSString, array and other variables. but when I am taking outlets of UIView, or any Instance as a UIViewController I am taking strong. Else actually I do not know the difference. – Arpit B Parekh Jul 04 '15 at 06:17
  • 4
    @ArpitParekh strong === retain: http://stackoverflow.com/questions/7796476/property-definitions-with-arc-strong-or-retain – DanZimm Jul 04 '15 at 06:18
  • But, when I am taking UIViewController as a variable, and I need to assign it as a strong proper, If I make it as a retain then my app crashes...this link support this. When adding it as a subview http://stackoverflow.com/questions/9144959/how-to-retain-view-after-addsubview-of-uiviewcontroller-with-arc – Arpit B Parekh Jul 04 '15 at 06:23
  • 1
    @ArpitParekh `retain` is no longer used as of ARC. You should replace it with `strong`. – Christian Schnorr Jul 04 '15 at 12:30

2 Answers2

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

Inder Kumar Rathore
  • 37,431
  • 14
  • 121
  • 176
4

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.

Munahil
  • 2,256
  • 1
  • 14
  • 21