__block needed for scalar variables if you want to change their value using code inside the block. Captured scalars are displayed as const inside the block and therefore cannot be changed. If you have a pointer to an object, the same difference applies - the captured pointer itself will be a const pointer and therefore cannot be changed, but the specified object can be changed by code inside the block. If you want to change the object that it points to, then the pointer itself must change, and therefore the pointer must be declared with the __block type. You never need to declare the object itself as __block , but only a pointer to the object, and only if the pointer needs to be changed.
If you have the right mental model, the blocks are not so confusing. It is important to know that the blocks are initially allocated on the stack and therefore disappear when the lexical region is destroyed as the stack frame stacks. If you want the block to freeze during the lifetime of the lexical area in which the block was created, move it to the heap using Block_copy() or send the Block_copy() message. When a block is copied to the heap, all captured const variables go, and all objects specified by these const variables are saved. When a block is removed from the heap, all objects pointed to by const variables are freed.
__block variables โunder the hoodโ have an additional layer of indirection used by the compiler (and which you donโt see) included in the block, so when the block is copied to the heap, t20> and the invisible pointers are configured to point to the new location of the heap of these variables __block . This means that the address of the __block variable can change, so be careful if you use this address. You can also see that the __block variable lives in a sense โoutsideโ the block, so these variables can be read and modified from code external to the block.
I was brief, but here you can find the best explanations listed in increasing difficulty:
http://ios-blog.co.uk/tutorials/programming-with-blocks-an-overview/
http://www.cocoawithlove.com/2009/10/how-blocks-are-implemented-and.html
http://www.mikeash.com/pyblog/friday-qa-2011-06-03-objective-c-blocks-vs-c0x-lambdas-fight.html
source share