ios Swift UITableView reloadData 在闭包中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26277371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift UITableView reloadData in a closure
提问by Jeef
I believe I'm having an issue where my closure is happening on a background thread and my UITableView isn't updating fast enough. I am making a call to a REST service and in my closure i have a tableView.reloadData()
call but it takes a few seconds for this to happen. How do I make the data reload faster (perhaps on the main thread?)
我相信我遇到了一个问题,我的关闭发生在后台线程上,而我的 UITableView 更新速度不够快。我正在调用 REST 服务,在我的闭包中,我有一个tableView.reloadData()
电话,但这需要几秒钟的时间。如何使数据重新加载更快(可能在主线程上?)
REST Query Function - using SwiftyJSON library for Decoding
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()
})
}
Once self.tableView.reloadData()
is called in my debugger
self.tableView.reloadData()
在我的调试器中调用一次
回答by Kirsteins
UIKit isn't thread safe. The UI should only be updated from main thread:
UIKit 不是线程安全的。UI 应该只从主线程更新:
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
Update. In Swift 3 and later use:
更新。在 Swift 3 及更高版本中使用:
DispatchQueue.main.async {
self.tableView.reloadData()
}
回答by Anand Suthar
You can also reload UITableView like this
你也可以像这样重新加载 UITableView
self.tblMainTable.performSelectorOnMainThread(Selector("reloadData"), withObject: nil, waitUntilDone: true)
回答by Sal
With Swift 3 use
与 Swift 3 一起使用
DispatchQueue.main.async {
self.tableView.reloadData()
}
回答by bubbaspike
You can also update the main thread using NSOperationQueue.mainQueue()
. For multithreading, NSOperationQueue is a great tool.
您还可以使用NSOperationQueue.mainQueue()
. 对于多线程,NSOperationQueue 是一个很好的工具。
One way it could be written:
一种写法:
NSOperationQueue.mainQueue().addOperationWithBlock({
self.tableView.reloadData()
})
回答by Maksim Kniazev
SWIFT 3:
快速 3:
OperationQueue.main.addOperation ({
self.tableView.reloadData()
})