gpt4 book ai didi

objective-c - 在异步 HTTP 请求的 completionHandler 中更新 View 时出现延迟

转载 作者:可可西里 更新时间:2023-11-01 06:19:01 25 4
gpt4 key购买 nike

在我的应用程序中,当用户按下按钮时,我会启动一个 HTTP 异步请求(使用 [NSURLConnection sendAsynchronousRequest...])并更改 UILabel 中的文本completionHandler block 。但是,此更改不会在请求结束时发生,而是在大约 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];
}];
}

当我尝试在 completionHandler 中创建一个 UIAlertView 时,会发生类似的行为。

- (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 的方式有关,但我不确定。非常感谢任何关于延迟发生原因的指导。

最佳答案

根据 The Apple Docs .

Threads and Your User Interface

If your application has a graphical user interface, it is recommended that you receive user-related events and initiate interface updates from your application’s main thread. This approach helps avoid synchronization issues associated with handling user events and drawing window content. Some frameworks, such as Cocoa, generally require this behavior, but even for those that do not, keeping this behavior on the main thread has the advantage of simplifying the logic for managing your user interface.

在主线程上调用您的 UI 更新可以解决这个问题。用对主线程的调用包围您的 UI 代码(如下)。

dispatch_async(dispatch_get_main_queue(), ^{
exampleLabel.text = [NSString stringWithFormat:@"%d", httpResponse.statusCode];
});

还有其他方法可以在主线程上进行调用,但是使用更简单的 GCD 命令就可以完成这项工作。再次查看 Threaded Programming Guide了解更多信息。

关于objective-c - 在异步 HTTP 请求的 completionHandler 中更新 View 时出现延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11386403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com