在更新UI之前出现NSURLConnection sendAsynchronousRequest completionHandler日志

oka*_*wei 1 objective-c ios sendasynchronousrequest

我有这个代码将json字符串发送到服务器

[NSURLConnection
 sendAsynchronousRequest:req
 queue:[[NSOperationQueue alloc] init]
 completionHandler:^(NSURLResponse *response,
                     NSData *data,
                     NSError *error)
 {

     if ([data length] >0 && error == nil)
     {

         NSLog(@"Done");

     }
     else if ([data length] == 0 && error == nil)
     {
         NSLog(@"Nothing was downloaded.");
         self.resultLabel.text=@"Done!";
         self.view.userInteractionEnabled = TRUE;
     }
     else if (error != nil){
         NSLog(@"Error = %@", error);
     }


 }];
Run Code Online (Sandbox Code Playgroud)

异步请求完成后,日志在完成后几乎立即显示.但是,这段代码:

self.resultLabel.text=@"Done!";
self.view.userInteractionEnabled = TRUE;
Run Code Online (Sandbox Code Playgroud)

在UI中显示10秒钟.有人知道为什么会这样吗?

kov*_*pas 12

您必须在主线程中执行所有UI更改:

....
if ([data length] == 0 && error == nil) {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.resultLabel.text=@"Done!";
        self.view.userInteractionEnabled = TRUE;
    });
}
....
Run Code Online (Sandbox Code Playgroud)