Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to access global variables in dispatch_async : "Variable is not Assignable (missing _block type specifier)" [duplicate]

In My dispach_async code block I cannot access global variables. I am getting 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 Anyone help me to find out the reason?

like image 835
Vaquita Avatar asked Jul 05 '12 04:07

Vaquita


1 Answers

You must use the __block specifier when you modify a variable inside a block, so the code you gave should look like this instead:

 __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 the variables referenced inside their bodies, so the captured variable must be declared mutable. And mutability is exactly what you need considering that you're essentially setting this thing.

like image 56
CodaFi Avatar answered Sep 21 '22 11:09

CodaFi