我有这个表视图控制器:
class EventListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIPickerViewDelegate, UIPickerViewDataSource {
// Event table view
@IBOutlet weak var eventTableView: UITableView!
var events: [Event] = []
...
我想从Web服务异步加载数据,这可能需要5秒钟的时间。
我有这个异步代码:
override func viewDidLoad() {
super.viewDidLoad()
...
// ApiClient is a custom wrapper for my API
ApiClient.sharedInstance.getEvents({
(error: NSError?, events: [Event]) in
// All this runs within an asynchronous thread
if let error = error {
println("Error fetching events")
println(error.localizedDescription)
}
self.events = events
// How to notify the table view?
})
...
数据加载正常,但表保持为空。一旦再次调用
viewWillAppear(...)
,数据就在表中。我需要通知表格视图吗?什么是最干净的方法/最佳实践?
谢谢!
最佳答案
只需调用self.eventTableView.reloadData()
即可。
如果闭包中的代码是在异步线程上执行的,则可能需要将该调用封装为dispatch_async
调用,以便在主线程上触发它(因为所有与UI相关的工作必须始终在主线程中运行):
// All this runs within an asynchronous thread
...
self.events = events
// Notify the tableView to reload its data.
// We ensure to execute that on the main queue/thread
dispatch_async(dispatch_get_main_queue()) {
self.eventTableView.reloadData()
}