温故而知新,重新阅读,有了新的收获,记录一下。
Note that we define a variable calledstartTimejust before the block is created, and then use
its value at the end of the block. Intuitively, this doesn’t seem to make sense, since by the time
the block is executed, the doWork:method has exited, so theNSDateinstance that thestartTimevariable is pointing to should already be released! This is a crucial point of block usage: if a blockaccesses any variables from “the outside” during its execution, then some special setup happenswhen the block is created, allowing the block access to those variables. The values contained bysuch variables will either be duplicated (if they are plain C types such as intor float) or retained
(if they are pointers to objects) so that the values they contain can be used inside the block. Whendispatch_asyncis called in the second line ofdoWork:,and the block shown in the code is created,startTimeis actually sent aretainmessage, whose return value is assigned to what is essentially anew static variable with the same name (startTime) inside the block.
The startTimevariable needs to be static inside the block so that code inside the block can’taccidentally mess with a variable that’s defined outside the block. If that were allowed all thetime, it would just be confusing for everyone. Sometimes, however, you actually do want to let
a block write to a value defined on the outside, and that’s where the __blockstorage qualifier(which we mentioned a couple of pages ago) comes in handy. If__blockis used to define avariable, then it is directly available to any and all blocks that are defined within the same scope.An interesting side effect of this is that__block-qualifiedvariables are not duplicated or retainedwhen used inside a block.
记录了在block 里面,不同的变量,不同的内存管理方式。