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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With