【发布时间】:2018-09-27 11:44:33
【问题描述】:
我注意到当我手动设置 tableview 数据源时,我必须保留对它的强引用,否则,cellForRowAt 将不会被调用。 (注意 numberOfRowsInSection 和 numberOfSections 被调用)
class YAExploreViewController: UIViewController {
...
dataSourceSubject
.subscribe(onNext: { dataSource in
// I'm not storing a strong reference to the dataSource, and cellForRowAt wouldn't get called
self.tableView.dataSource = dataSource
self.tableView.reloadData()
})
.disposed(by: self.bag)
...
}
解决方法:
class YAExploreViewController: UIViewController {
var exploreDataSource: YAExploreDataSource?
...
dataSourceSubject
.subscribe(onNext: { dataSource in
// I'm storing a strong reference to the dataSource, and cellForRowAt got called
self.dataSource = dataSource
self.tableView.dataSource = self.dataSource
self.tableView.reloadData()
})
.disposed(by: self.bag)
...
}
我注意到 tableView 的 dataSource 属性上有一个描述:
充当表格视图的数据源的对象。数据 source 必须采用 UITableViewDataSource 协议。数据源 不保留。
我想知道这是否相关。
谢谢
【问题讨论】:
-
是的,您的第一个示例中的
dataSource的范围在onNext块内,当块完成时,该类被释放,因为没有人保留。在第二个例子中不再是这种情况了。控制器对它有很强的引用。此外,您应该在onNext块内使用week self,以避免控制器的保留周期。