3

When I create properties for an application in iOS, when should I use "assign"? When should I use "retain"?

Are there any benefits of one over the other?

Jonathan Arbogast
  • 9,620
  • 4
  • 35
  • 47
user496949
  • 83,087
  • 147
  • 309
  • 426

2 Answers2

8

Assign is usually used for primitive types, the compiler will create the setter such that all that is done is a simple assign operation.

Whereas setting a value on a property with the 'retain' (now called "strong" with ARC) qualifier causes your backing instance variable to take ownership of (in other words retain) the object that was set.

With objects, if you don't want to take ownership as described and you're using ARC, you would most likely want to use the 'weak' qualifier instead of 'assign'.

Kaan Dedeoglu
  • 14,765
  • 5
  • 40
  • 41
4

If you are using ARC, you don't need to use retain because you are not manually managing the memory.

Retain: if you are non-using ARC, you need to manually manage the memory of your app. In this case, if you use retain for one variable, you are incrementing the count by one. Then, the count need to reach 0 to be deallocated.

Assign: when calling the getter of an assign property, it returns a reference to the actual data. Typically you use this attribute when you have a property of primitive type.

Strong: replacement for the retain attribute, as part of Objective-C Automated Reference Counting (ARC). In non-ARC code it's just a synonym for retain. You use for the objects you want to keep a reference. In the other hand we have weak:

@property (nonatomic, strong) UIColor *myColor
@property (nonatomic, assign) BOOL myBOOL

Anyways, this link is really useful and it's better explained than here. Objective-C declared @property attributes (nonatomic, copy, strong, weak)

Community
  • 1
  • 1
Alex
  • 1,061
  • 10
  • 14