Swift UITableView reloadData在闭包中

我相信我有一个问题,我的closures发生在后台线程和我的UITableView没有足够快的更新。 我打电话给一个REST服务,并在我的closures,我有一个tableView.reloadData()调用,但这需要几秒钟发生。 如何使数据重新加载更快(也许在主线程上)?

REST查询函数 – 使用SwiftyJSON库进行解码

 func asyncFlightsQuery() { var url : String = "http://127.0.0.1:5000/flights" var request : NSMutableURLRequest = NSMutableURLRequest() request.URL = NSURL(string: url) request.HTTPMethod = "GET" NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, networkData: NSData!, error: NSError!) -> Void in var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil // Parse with SwiftyJSON let json = JSON(data: networkData) // Empty out Results array self.resultArray = [] // Populate Results Array for (key: String, subJson: JSON) in json["flights"] { print ("KEY: \(key) ") print (subJson["flightId"]) print ("\n") self.resultArray.append(subJson) } print ("Calling reloadData on table..??") self.tableView.reloadData() }) } 

一旦self.tableView.reloadData()在我的debugging器中被调用

UIKit不是线程安全的。 UI只能从主线程更新:

 dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() } 

更新 。 在Swift 3和以后使用:

 DispatchQueue.main.async { self.tableView.reloadData() } 

你也可以像这样重新加载UITableView

 self.tblMainTable.performSelectorOnMainThread(Selector("reloadData"), withObject: nil, waitUntilDone: true) 

随着Swift 3的使用

 DispatchQueue.main.async { self.tableView.reloadData() } 

SWIFT 3:

 OperationQueue.main.addOperation ({ self.tableView.reloadData() }) 

你也可以使用NSOperationQueue.mainQueue()来更新主线程。 对于multithreading,NSOperationQueue是一个很好的工具。

可以写的一个方法是:

 NSOperationQueue.mainQueue().addOperationWithBlock({ self.tableView.reloadData() }) 

更新 : DispatchQueue是这样做的方式