【发布时间】:2019-08-01 07:15:31
【问题描述】:
我有以下模型、基本 UITableViewController 类和 UITableViewController 的子类:
型号
class Product {
var title: String
var prices: [Int]
}
UITableViewController - 超类
class BaseTableController: UITableviewController {
var items: [Product] = [Product]()
override func viewDidLoad() {
super.viewDidLoad()
fetchData()
}
// MARK: - UITableViewDataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
let item = items[indexPath.item]
Logger.debug("FOUND \(item.prices.count) PRICES")
return cell
}
// MARK: - Data
func fetchData() {
let dispatchGroup = DispatchGroup()
items.forEach { (item) in
dispatchGroup.enter()
APIService.shared.getPrices(product: item) { (prices) in
item.prices = prices
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: DispatchQueue.main) {
self.tableView.reloadData()
}
}
}
UITableViewController - 子类
class MyFancyTable: BaseTableController {
override var items: [Product] {
set {}
get {
return [
Product(title: "FOOD"),
Product(title: "DRINK")
]
}
}
}
我将使用 MyFancyTable 从不同的产品类别中获取价格。
当 API 返回响应时,它将更新 items 变量中的价格,然后我重新加载表格。
但是,当我在子类 (MyFancyTable) 中覆盖 items 时,即使在 API 回调期间价格已更新,记录器(在 cellForRowAtIndexPath 中)仍会读取零价格。好像从来没有更新过一样。
日志结果:
FOUND 0 PRICES - 食品
FOUND 0 PRICES - 饮料
我可以确认 API 返回多个价格。
我们将不胜感激。谢谢!
【问题讨论】:
-
你永远不会进入 DispatchGroup。
-
我看不出你是怎么拉东西的。
-
很抱歉我删除了很多代码以使其更具可读性(代码部分已更新)。
-
您是否设置了断点以确保调用
reloadData()? -
@Xcoder,是的...我可以确认调用了
reloadData()。然后它再次转到cellForRowAtIndexPath,打印出两种产品的 0 个价格。
标签: swift uitableview datasource subclass