在我的应用程序中,当用户按下按钮时,我启动一个 HTTP 异步请求(使用[NSURLConnection sendAsynchronousRequest...]
)并更改文本UILabel
in the completionHandler
堵塞。但是,此更改不会在请求结束时发生,而是在大约 2-3 秒后发生。下面是导致此行为的代码片段。
- (IBAction)requestStuff:(id)sender
{
NSURL *url = [NSURL URLWithString:@"http://stackoverflow.com/"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:
^(NSURLResponse *response, NSData *data, NSError *error)
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
exampleLabel.text = [NSString stringWithFormat:@"%d", httpResponse.statusCode];
}];
}
当我尝试创建一个时,会发生类似的行为UIAlertView
在 - 的里面completionHandler
.
- (IBAction)requestStuff:(id)sender
{
NSURL *url = [NSURL URLWithString:@"http://stackoverflow.com/"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:
^(NSURLResponse *response, NSData *data, NSError *error)
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if ([httpResponse statusCode] == 200) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"It worked!"
message:nil
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
}];
}
不过,有一个小小的区别,那就是屏幕会在以下情况下变暗:[alert show]
被执行。与之前的场景一样,警报本身仅在 2-3 秒后出现。
我猜测这与应用程序线程处理 UI 的方式有关,但我不确定。任何有关延迟发生原因的指导将不胜感激。
根据苹果文档.
线程和您的用户界面
如果您的应用程序有图形用户界面,建议您接收与用户相关的事件并从应用程序的启动界面更新主线程. 这种方法有助于避免与处理用户事件和绘制窗口内容相关的同步问题。某些框架(例如 Cocoa)通常需要此行为,但即使对于那些不需要此行为的框架,将此行为保留在主线程上也具有简化管理用户界面的逻辑的优点。
在主线程上调用 UI 更新可以解决这个问题。通过调用主线程(如下)来包围您的 UI 代码。
dispatch_async(dispatch_get_main_queue(), ^{
exampleLabel.text = [NSString stringWithFormat:@"%d", httpResponse.statusCode];
});
还有其他方法可以在主线程上进行调用,但使用更简单的 GCD 命令就可以完成这项工作。再次,请参阅线程编程指南了解更多信息。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)