Unable to access global variables in dispatch_async : "Variable is not Assignable (missing _block type specifier)"
34,681
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.
Author by
Vaquita
Mobile application developer focusing on Android and iOS apps.
Updated on August 29, 2020Comments
-
Vaquita over 3 years
In My dispach_async code
block
I cannot accessglobal variables
. I am getting this errorVariable 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?
-
S.Philip almost 11 yearsPlease note that there are two underscores in
__block
-
newacct about 10 yearsBut 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 usestextString
, which can be executed later. -
CodaFi about 10 yearsWithout 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. -
Nikesh K over 6 yearsTo 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)