问题
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
});
- What happens the second time this block is triggered?
- How can myNumber be still there if the block will deallocate after running?
- 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:
- 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.
- 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.
- 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