49

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?

Alex Cio
  • 6,014
  • 5
  • 44
  • 74
jay
  • 3,517
  • 5
  • 26
  • 44

1 Answers1

139

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.

CodaFi
  • 43,043
  • 8
  • 107
  • 153
  • 17
    Please note that there are **two underscores** in `__block` – S.Philip Jun 21 '13 at 06:30
  • But this solution is still useless -- the block is executed once asynchronously. So even if it could assign to the local variable `testString`, who can use it? The only thing I can think of if there's another block in this scope that also uses `textString`, which can be executed later. – newacct Mar 02 '14 at 06:42
  • Without surrounding context, or code that isn't basically pseudo-code, how did you come to that determination? For all you know, the OP could have omitted dispatch_group logic, or perhaps some surrounding KVO `will/didChangeValueForKey:` calls in the block. Point is: you missed the point of the question. – CodaFi Mar 02 '14 at 08:25
  • 1
    To assign a value for a Global variable __block works fine as mentioned above. This means, we can modify the value of textString inside the block. At the same time, accessing "self" inside the block will create a retain cycle. So try using weak instance of self inside the block (create weak self like this __weak typeof(self) wkSelf = self) – Nikesh K Aug 16 '17 at 08:18