在代码块中设置UILabel文本 [英] Set UILabel text within code block
问题描述
我的NSURLConnection sendAsynchronousRequest有一个代码块,当我尝试设置UILabel的文本时,即使值存在,也永远不会设置文本。这是我的代码:
I have a code block for my NSURLConnection sendAsynchronousRequest, and when I try to set a UILabel's text, the text is never set, even though the values are there. Here's my code:
NSString *address = [addresses objectAtIndex:indexPath.row];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://myurl.com/%@", address]]];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if ([data length] > 0 && error == nil)
{
NSString *dataOfData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(![dataOfData isEqualToString:@"ERROR: address invalid"]) {
[balanceLabel setText:[NSString stringWithFormat:@"Balance: %@", dataOfData]];
if(data) {
qrCodeButton.alpha = 1;
}
} else {
errorLabel.text = @"This address is invalid.";
}
}
else if ([data length] == 0 && error == nil)
{
NSLog(@"Nothing was downloaded.");
[balanceLabel setText:@"Server Error, Please Try Again"];
}
else if (error != nil){
NSLog(@"Error = %@", error);
}
}];
为什么UILabel的文字从未设定?代码块有限制吗?如果是这样,我将如何解决我的问题?干杯!
Why is the UILabel's text never set? Is there a limitation to code blocks? If so, how would I fix my problem? Cheers!
推荐答案
这是因为NSOperationQueue不是主线程。你在做什么是非法的。令人遗憾的是,没有必要!只需说:
It is because an NSOperationQueue is not the main thread. What you're doing is illegal. And the sad thing is that there is no need for it! Just say:
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
// ... and the rest exactly as you have it now
全部修复。您的请求在后台线程上是异步的,但是当它在完成处理程序上返回给您时,您将在主线程上并且能够与接口等通信。
All fixed. Your request is asynchronous on a background thread, but when it comes back to you on the completion handler, you'll be on the main thread and able to talk to the interface etc.
这篇关于在代码块中设置UILabel文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!