Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use weak pointer for delegation?

Tags:

objective-c

I can't understand why it is correct to define a delegate with weak pointer :

@property (nonatomic,weak) id delegate; 

I can't realize why isn't necessary to retain a reference to the delegate... i don't want the object that i use as the delegate to be deallocated... thus, i would prefer using a strong reference not a weak!

In many cases the delegate is the same object where the instance of my class will be created, in this case creating a weak reference would be a great solution to avoid retain cycle... but what if I choose a totally different object as the delegate ?

I searched for other questions on stack overflow but I can't find something that can help me to fully understand this situation.

like image 935
MatterGoal Avatar asked Dec 09 '11 17:12

MatterGoal


People also ask

Why We Use weak for delegate in Swift?

However, using a strong delegate property in a , b will never get deallocated since a is holding on to b strongly. Using a weak reference, as soon as b loses the strong reference from c , b will dealloc when c deallocs. Usually this is the intended behaviour, which is why you would want to use a weak property.

Why are delegates weak?

As a general rule, delegates should be marked as weak because most delegates are referencing classes that they do not own. This is definitely true when a child is using a delegate to communicate with a parent. Using a weak reference for the delegate is what the documentation recommends.


1 Answers

The reason that objects weakly retain their delegates is to avoid retain cycles. Imagine the following scenario: object a creates b and retains it, then sets itself as b's delegate. a is released by its owner, leaving a retain cycle containing a and b. This is actually a very common scenario. Consider a view controller that owns a view and acts as that view's delegate. In this case, the view should not retain the controller—as a mater of proper MVC architecture and to prevent retain cycles.

like image 63
Barry Wark Avatar answered Nov 08 '22 23:11

Barry Wark