Static variable inside block

江枫思渺然 提交于 2019-12-11 00:53:48

问题


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      
});
  1. What happens the second time this block is triggered?
  2. How can myNumber be still there if the block will deallocate after running?
  3. Is doing this OK? I mean will this practice cause any problem, like the block leaking because it is unable to be released?

回答1:


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.

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:

  1. What happens the second time this block is triggered?

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.

  1. How can myNumber be still there if the block will deallocate after running?

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.

  1. Is doing this OK? I mean will this practice cause any problem, like the block leaking because it is unable to be released?

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




回答2:


maybe we can answer using "C" underlying logic.. closure-> blocks -> pointer to std C functions, to "C" static logic occurs-> globals (OMG!)



来源:https://stackoverflow.com/questions/46402330/static-variable-inside-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!