ios 无法访问 dispatch_async 中的全局变量:“变量不可分配(缺少 _block 类型说明符)”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11337975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unable to access global variables in dispatch_async : "Variable is not Assignable (missing _block type specifier)"
提问by Vaquita
In My dispach_async code block
I cannot access global variables
. I am getting this error Variable is not Assignable (missing _block type specifier)
.
在我的 dispach_async 代码中,block
我无法访问global variables
. 我收到此错误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?
谁能帮我找出原因?
回答by CodaFi
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 说明符,因此您提供的代码应如下所示:
__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.
块捕获其体内引用的变量的状态,因此必须将捕获的变量声明为可变的。考虑到您实际上是在设置这个东西,因此可变性正是您所需要的。