Variable assigned in dispatch block coming back null

后端 未结 2 1977
天涯浪人
天涯浪人 2021-01-27 04:47

I\'m trying to make a network call run in a background thread so it doesn\'t freeze my app while it\'s waiting.

The call happens when I do:

nextTime = [m         


        
相关标签:
2条回答
  • 2021-01-27 04:58

    That's because you're setting it inside an asynchronous block, and asynchronous blocks return immediately. If you look at the time stamps of the two logs, you'll see that the outer log is actually being posted before both the inner log, and the setting of the variable.

    From the GCD docs on dispatch_async():

    This function is the fundamental mechanism for submitting blocks to a dispatch queue. Calls to this function always return immediately after the block has been submitted and never wait for the block to be invoked. The target queue determines whether the block is invoked serially or concurrently with respect to other blocks submitted to that same queue. Independent serial queues are processed concurrently with respect to each other.

    0 讨论(0)
  • 2021-01-27 05:07

    Your "outside" NSLog statement should actually go in that inner dispatch_async block that is set to run on the main thread, because that block will execute after you've set the value of nextTime. Any code you place below your asynchronous block call will likely execute way before the code inside the block.

    0 讨论(0)
提交回复
热议问题