Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a delegate retained?

I know , the delegate is never retained! Ever!

But can anyone explain me why delegate is never retained ?...

Thanx in advance

like image 217
Kalpesh Avatar asked Dec 20 '12 12:12

Kalpesh


People also ask

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.

Why are delegates weak?

When you define a delegate object as property, it's used a weak reference in the object it is defined in(lets say A, i.e. the delegate object is a property of A). The delegate is assigned when you init A(let's say in B), then most likely you would assign A. delegate to self, which is acturally B.


3 Answers

It's a memory management thing.

Objective-C works with reference counts to keep the memory clean. This does mean that it can't detect cyclic relationships.

Example:

  • Object A owns object B. Object B is retained by object A.
  • Object B has a delegate that is object A. Object A is retained by object B.
  • Object C owns object A. Object A is retained by object C.
  • Object A now has a retainCount of 2, and object B has a retainCount of 1
  • Object C gets freed, and releases object A
  • Object A and B now have a retainCount of 1, because they own eachother. The system will not free them, because the retainCount is still 1 (still owned by another object)
  • Memory leak!
like image 120
Tom van der Woerdt Avatar answered Oct 23 '22 01:10

Tom van der Woerdt


It's up to you. If you declare it to be retained (strong in ARC) it'll be retained.

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

like image 45
djromero Avatar answered Oct 23 '22 00:10

djromero


To expand on djromero's answer:

If you have a UIViewController which contains a UITableView, the controller will be most likely retaining the table and it will be it's delegate / dataSource. If the table retains the delegate / dataSource, then they will be retaining each other and thus never getting released.

like image 2
Ismael Avatar answered Oct 23 '22 00:10

Ismael