property “assign” and “retain” for delegate

1 Answer

active

oldest

votes

up vote

13

down vote

accepted

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?

你可能感兴趣的:(property)