Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

property "assign" and "retain" for delegate

For iOS developers, delegates are used almost everywhere.

And seems like that we need to use "assign" instead of retain for a delegate like this

@property(assign) id delegate;

The reason is to avoid the circular loop issue Why are Objective-C delegates usually given the property assign instead of retain?

I saw a lot of code and they still used "retain". So the question here is will we still get the circular loop issue if we use retain for a delegate?

Thanks

like image 480
Forrest Avatar asked Mar 03 '11 03:03

Forrest


People also ask

What is difference between assign and retain?

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 documentation says:

Retaining an object creates a strong reference, and an object cannot be deallocated until all of its strong references are released. If two objects retain each other, neither object ever gets deallocated because the connection between them cannot be broken

As an example, let's consider a UITableViewController that implements UITableViewDelegate protocol. UITableView is retained by it's view controller, although the UITableView does not retain it's delegate.

As said on the document above, UITableViewController will only complete its deallocation when all its strong references get released. Since the UITableView that has the UItableViewController as a delegate doesn't retain it, when the owner of UItableViewController calls release on it, the retain count will go to zero and the dealloc method will get called.

Now imagine that UITableView retains its delegate. UITableViewController will have a retain count of at least +2. One with it's owner and another with UITableView. When UITableViewController's owner calls release on it, the retain count will go to +1, and not to zero as it was expected, and so the dealloc method won't get called until the retain count reaches zero. To reach zero, UITableViewController would need to release its UITableView that would then release its delegate (UITableViewController). Because the UITableViewController will only disposes its view (UITableView) when deallocing this moment would never happen because the retain count won't go bellow +1.

(let's not take in consideration memory warnings and any other possible case...I just saw that ViewController/View is not the best option for this example, but I've written too much already. :))

Does that make sense?

like image 52
vfn Avatar answered Sep 19 '22 08:09

vfn