Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between 'weak' and 'assign' in delegate property declaration

Whats the difference between this:

@property (nonatomic, weak) id  <SubClassDelegate> delegate; 

and this:

@property (nonatomic, assign) id  <SubClassDelegate> delegate; 

I want to use property for delegates.

like image 999
Firdous Avatar asked Feb 24 '12 09:02

Firdous


People also ask

Why delegates are declared weak?

The Swift book says that "to prevent strong reference cycles, delegates are declared as weak references."

What is the difference between retain and assign and when to use weak?

Assign creates a reference from one object to another without increasing the source's retain count. Retain creates a reference from one object to another and increases the retain count of the source object.

Why delegate is never retained?

The rule is to not retain it because it's already retained elsewhere and more important you'll avoid retain cycles.


1 Answers

The only difference between weak and assign is that if the object a weak property points to is deallocated, then the value of the weak pointer will be set to nil, so that you never run the risk of accessing garbage. If you use assign, that won't happen, so if the object gets deallocated from under you and you try to access it, you will access garbage.

For Objective-C objects, if you're in an environment where you can use weak, then you should use it.

like image 144
yuji Avatar answered Oct 12 '22 05:10

yuji