我正在使用 swift 3,我有一个从数据库获取数据的 TableView。当 TableView 到达第 3 行时,我从数据库中获取更多数据。一切正常,但我有大约 3 个不同的 TableViews 可以使用该功能,所以我隔离逻辑并将其放入它自己的函数中,这样我就可以为其他 3 个 Tableviews 调用它。这是我的代码,可以正常工作
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)
}
}
tôi ở đây HomeC().reloadTable() 上收到 nil 错误,这是可以理解的,我能解决这个问题吗?该错误仅在我尝试获取更多数据时发生,因为新函数看不到 reloadTable 函数及其内部的所有内容已在 HomeC 类/ Controller 中初始化.
看起来设计很糟糕。当您直接从另一个对象调用 reloadTable()
时,会增加代码的复杂性。其他对象不应该知道 Controller 的内部实现。您可以将 hoàn thành
block 添加到 getMoreData
(方法名称以小写字母开头)签名。此 block 将调用而不是 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() })
Tôi là một lập trình viên xuất sắc, rất giỏi!