简体   繁体   English

下载网页内容后快速更改标签文本

[英]Swift changing text of a label after downloading content of a web page

I have this code and I want to change content of a label with a text from web 我有这段代码,我想用网络上的文本更改标签的内容

var url = NSURL(string: "SOME_URL");
var task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: {
(data, response, error) -> Void in


if error == nil {
self.label.text = "SOME_TEXT" // not working

dispatch_async(dispatch_get_main_queue()){
     self.label.text = "SOME_TEXT" // working
     }

}
else{
    println("Error")
}

})

task.resume()

Why do I have to use dispatch_async(dispatch_get_main_queue()){ ... } to change the content of the label ? 为什么必须使用dispatch_async(dispatch_get_main_queue()){ ... }来更改标签的内容?

The principe of iOS: you have only 1 thread that can modify your UI. iOS的基本原理:您只有1个线程可以修改UI。 It's called UI Thread. 它称为UI线程。 Whenever you want to change the UI content, all functions that change your UI content must be called in the UI Thread. 每当您要更改UI内容时,必须在UI线程中调用所有更改UI内容的函数。 In your case, the handler is executed in a background thread, hence you have to put the self.label.text = "SOME_TEXT" in the UI Thread. 在您的情况下,处理程序在后台线程中执行,因此您必须将self.label.text = "SOME_TEXT"放入UI线程中。

It's a very common pattern in GUI programming. 这是GUI编程中非常常见的模式。

Basically the main message loop runs single threaded without the cost of synchronizing everything. 基本上,主消息循环运行单线程,而无需同步所有内容。 That means that if you want to interact with your window you need to do it on the main GUI thread -- that's what dispatch does, it posts a message on the message queue and the loop interprets it, bringing your code on its thread. 这意味着,如果要与窗口进行交互,则需要在主GUI线程上进行操作-这就是分派的工作,它在消息队列上发布一条消息,然后循环对其进行解释,从而将您的代码置于其线程上。

It's both for simplicity and for performance. 为了简单和性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM