How does a Block capture the variables outside of its enclosing scope?

前端 未结 3 784
再見小時候
再見小時候 2020-12-01 09:45

I know that an Objective-C Block can capture and set the value of variables outside of its enclosing scope. How does it do that?

3条回答
  •  爱一瞬间的悲伤
    2020-12-01 10:08

    Basically, the block "object" contains an variable inside the block object (like an "instance variable" of the block object) for every captured local variable. (Josh Caswell's answer provides more details about how it is implemented.) When the block is created, the value of each captured local variable at that time is copied into the corresponding variable inside the block. Whenever the variable is used inside the block, it uses this variable inside the block instead.

提交回复
热议问题