Failed to access global variables in dispatch_async: "Variable not assigned (missing _block type specifier)"

In my code dispash_async block I can not access global variables . I get this error Variable is not Assignable (missing _block type specifier) .

 NSString *textString; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, (unsigned long)NULL), ^(void) { textString = [self getTextString]; }); 

Can someone help me figure out the reason?

+46
multithreading ios objective-c objective-c-blocks grand-central-dispatch
Jul 05 2018-12-12T00:
source share
1 answer

You should use the __block specifier when changing a variable inside a block, so the code you specified should look like this:

  __block NSString *textString; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, (unsigned long)NULL), ^(void) { textString = [self getTextString]; }); 

Blocks capture the state of variables referenced within their bodies, so the captured variable must be declared mutable. And volatility is exactly what you need, given that you basically install this thing.

+135
Jul 05 2018-12-12T00:
source share



All Articles