块内的静态变量 [英] Static variable inside block
问题描述
当我在这样的块内声明静态变量时会发生什么?
What happens when I declare a static variable inside a block like this?
dispatch_async(dispatch_get_main_queue(), ^{
static NSInteger myNumber;
// do stuff with myNumber
});
- 第二次触发该块会发生什么?
- 如果该块在运行后将取消分配,myNumber怎么还在那里?
- 这样可以吗?我的意思是,这种做法会引起任何问题,例如由于无法释放而导致块泄漏吗?
推荐答案
块规范没有明确提及如何处理块内的static
变量,只是块主体是与函数主体相同的复合语句.因此,语义与在函数中声明的static
变量的语义相同,即它们是全局生存期的变量,只能在声明它们的范围内通过名称直接访问.
The block specification does not explicitly mention how static
variables within blocks are handled, just that the block body is a compound statement which is just the same as the body of a function. Therefore the semantics are the same as for static
variables declared in a function, that is they are variables of global lifetime which are only directly accessible by name within the scope they are declared in.
每次评估 block文字(^{...}
)时,都会构造一个 value 块.此值包含一个标准的C函数指针,该指针指向块主体的已编译代码,就像其他任何复合语句一样,它们在编译时也会生成一次.
A block value is constructed each time a block literal (^{...}
) is evaluated. This value contains a standard C function pointer to the compiled code of the block body, which like any other compound statement is generated once at compile time.
您的问题的答案就是这样:
The answers to your questions just follow from this:
- 第二次触发该阻止会发生什么?
第二次执行带有局部static
变量的函数时,发生同样的事情,函数主体看到了先前存储在变量中的值.
Same thing that happens the second time a function with a local static
variable is executed, the function body sees the value previously stored in the variable.
- 如果该块在运行后将取消分配,myNumber怎么还在那里?
因为它是块值,其中包括任何关联的捕获变量,所以将其释放;包含任何static
变量的已编译代码始终存在.
Because it is the block value, which includes any associated captured variables, which is deallocated; the compiled code, which includes any static
variables, always exists.
- 这样可以吗?我的意思是,这种做法会引起任何问题,例如由于无法释放而导致块泄漏吗?
执行此操作与在函数中执行此操作相同.如果static
是Objective-C对象类型,则存储在其中的引用可能会泄漏"-就像使用标准全局变量一样.除非您将对块本身的引用(直接或间接通过引用链)存储在static
变量中,否则不会阻止该块值的重新分配.
Doing this is the same as doing it within a function. If the static
is of Objective-C object type then references stored in it may "leak" - just as with standard global variables. The block value will not be prevented from deallocation unless you store a reference to the block itself (directly or indirectly via a chain of references) in the static
variable.
HTH
这篇关于块内的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!