ChaCha
ChaCha

Reputation: 31

Why don't the UITableViewDataSource or UITableViewDelegate need define for weak in UITableView?

I will write my own delegate or dataSource according to UITableView, but I don't know how to define it. In UITableView:

var dataSource: UITableViewDataSource!
var delegate: UITableViewDelegate!

It's not need define for 'weak' ?

Upvotes: 2

Views: 1154

Answers (1)

drewag
drewag

Reputation: 94733

If you are referring to using separate objects, you most likely do not want to mark them as weak. Take this example:

class MyViewController: UIViewController {
    @IBOutlet var tableView: UITableView!
    var dataSource: UITableViewDataSource
    var delegate: UITableViewDelegate

    init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
        self.dataSource = SomeCustomDataSource();
        self.delegate = SomeCustomDelegate();

        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)

        self.tableView.dataSource = self.dataSource;
        self.tableView.delegate = self.delegate;
    }
}

Here, the view controller has a strong reference to the tableView. The tableView does not hold a strong reference to its dataSource or its delegate so it is important that the view controller hold a strong reference to each of those.

The place in the delegate pattern that you should use a weak reference is for the object that is defining and using a delegate. In this case, it is the UITableView itself. It is very common for the "delegate" in a delegate pattern to have a strong reference to the thing it is the delegate for. For example, many people make the view controller that the UITableView is in, the delegate and datasource for it. If the tableView had a strong reference to its delegate, there would be a circular reference – the controller would have a strong reference to the table view and the table view would have a strong reference to the controller (its delegate).

Upvotes: 3

Related Questions