【问题标题】:Why don't the UITableViewDataSource or UITableViewDelegate need define for weak in UITableView?为什么 UITableViewDataSource 或 UITableViewDelegate 不需要为 UITableView 中的弱定义?
【发布时间】:2014-07-30 03:08:54
【问题描述】:
我会根据UITableView写自己的delegate或者dataSource,但是不知道怎么定义。
在 UITableView 中:
var dataSource: UITableViewDataSource!
var delegate: UITableViewDelegate!
“弱”不需要定义?
【问题讨论】:
标签:
ios
uitableview
swift
【解决方案1】:
如果您指的是使用单独的对象,您很可能不想将它们标记为弱。举个例子:
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;
}
}
这里,视图控制器对tableView有一个强引用。 tableView 不持有对其数据源或委托的强引用,因此视图控制器持有对它们中的每一个的强引用很重要。
委托模式中您应该使用弱引用的地方是定义和使用委托的对象。在这种情况下,它是 UITableView 本身。委托模式中的“委托”对它所代表的事物有很强的引用是很常见的。例如,许多人制作 UITableView 所在的视图控制器、委托和数据源。如果 tableView 对其委托有一个强引用,就会有一个循环引用——控制器将对 table view 有一个强引用,而 table view 将对控制器(它的委托)有一个强引用。