在我的应用程序中,当用户按下按钮时,我启动 HTTP 异步请求(使用[NSURLConnection sendAsynchronousRequest...]
)并更改块UILabel
中的文本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 有关,但我不确定。任何有关延迟发生原因的指导将不胜感激。