无法访问dispatch_async中的全局变量:"变量不可分配(缺少_block类型说明符)"

Vaq*_*ita 49 multithreading objective-c grand-central-dispatch ios objective-c-blocks

在我的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];
});
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮我找出原因吗?

Cod*_*aFi 138

修改块内的变量时必须使用__block说明符,因此您给出的代码应如下所示:

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

块捕获其体内引用的变量的状态,因此捕获的变量必须声明为可变的.考虑到你实际上是设置这个东西,可变性正是你需要的.

  • 请注意,`__block`中有**两个下划线** (17认同)