Delay when updating view in the completionHandler of an async HTTP request

后端 未结 3 1345
生来不讨喜
生来不讨喜 2021-01-06 14:46

In my app when the user presses a button I start a HTTP asynchronous request (using [NSURLConnection sendAsynchronousRequest...]) and change the text of U

3条回答
  •  独厮守ぢ
    2021-01-06 15:09

    According to 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.

    Calling your UI updates on the main thread would solve this problem. Surround your UI code with a call to the main thread (below).

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

    There are other ways to do calls on the main thread, but using the simpler GCD commands would do the job. Again, see the Threaded Programming Guide for more info.

提交回复
热议问题