我使用的是swift 3,我有一个从数据库获取数据的TableView。当TableView到达倒数第三行时,我会从数据库中获得更多数据。一切都正常工作,但我有大约3个不同的TableView可以使用该功能,所以我正在隔离逻辑并将其放入自己的函数中,这样我就可以为其他3个TableView调用它。这是我的代码,工作正常
class HomeC: UIViewController,UITableViewDataSource,UITableViewDelegate {
var streamsModel = streamModel()
var timeLineModel = TimeLineModel()
func reloadTable() {
// This gets data from the database
timeLine.Stream(streamsModel: streamsModel, TableSource: TableSource, Controller: self, post_preview: post_preview, model: timeLineModel)
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if timeLineModel.Counter <= streamsModel.Locations.count {
if indexPath.row == self.streamsModel.Locations.count - 3 {
// I now get 20 more rows from the database
timeLineModel.Page += 1
reloadTable()
timeLineModel.Counter += 20
}
}
}
}
上面的代码工作正常,但我必须在其他3个TableView中使用相同的逻辑,我想将该逻辑放入1个函数中,然后调用它。这是我的新代码
class TimeLine: NSObject {
func GetMoreData(streamsModel: streamModel, timeLineModel: TimeLineModel, indexPath: IndexPath) {
if timeLineModel.Counter <= streamsModel.Locations.count {
if indexPath.row == streamsModel.Locations.count - 3 {
timeLineModel.Page += 1
// I Get a nil error here
HomeC().reloadTable()
timeLineModel.Counter += 20
}
}
}
}
then I call it here
class HomeC: UIViewController,UITableViewDataSource,UITableViewDelegate {
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
timeLine.GetMoreData(streamsModel: streamsModel, timeLineModel: timeLineModel, indexPath: indexPath)
}
}
我在HomeC().reloadTable()上得到了零错误,这是可以理解的,有什么办法可以解决吗?只有当我试图获取更多数据时才会出现错误,因为新函数看不到reloadTable函数及其内部的所有内容已经在HomeC类/控制器中初始化。
看起来设计不好。当您从另一个对象直接调用reloadTable()
时,会增加代码的复杂性。其他对象不应该知道控制器的内部实现。您可以将complete
块添加到getMoreData
(方法名称以小写字母开头)签名中。此块将调用而不是HomeC().reloadTable()
func getMoreData(streamsModel: streamModel,
timeLineModel: TimeLineModel,
indexPath: IndexPath,
complete: @escaping () -> Void) {
if timeLineModel.Counter <= streamsModel.Locations.count {
if indexPath.row == streamsModel.Locations.count - 3 {
timeLineModel.Page += 1
timeLineModel.Counter += 20
complete()
}
}
}
}
使用:
timeLine.GetMoreData(streamsModel: streamsModel,
timeLineModel: timeLineModel,
indexPath: indexPath,
complete: { reloadTable() })