什么时候该用__block

come from:http://stackoverflow.com/questions/17823167/when-to-use-block-keyword-on-object-references-with-arc

__block is needed for scalar variables if you want to change their value with code inside the block. Captured scalars appear as const inside the block and therefore cannot be changed. If you have a pointer to an object, the same distinction applies--the captured pointer itself will be a const pointer and therefore cannot be modified, but the object pointed to can be modified by code inside the block. If you want to change the object pointed to, then the pointer itself must change, and so the pointer must be declared with the __block type. It is never necessary to declare the object itself as __block, but only the pointer to the object, and only if the pointer must be changed.

If you have the right mental model, blocks aren't that confusing. It is important to know that blocks are initially allocated on the stack, and so vanish when the lexical scope is destroyed as the stack frame is popped. If you want the block to hang around past the lifetime of the lexical scope in which the block was created, move it to the heap using Block_copy() or sending it a -copy message. When a block is copied to the heap, all the captured const variables go along, and any objects these const variables point to are retained. When the block is removed from the heap, all objects pointed to by the const variables are released.

__block variables "under the hood" have an extra layer of indirection the compiler uses (and that you don't see) included in the block, so when the block is copied to the heap, so are the captured __block variables, and the invisible pointers are adjusted to point to the new heap location of these __block variables. This means the address of a __block variable can change, so be careful if you use that address. You can also see that a __block variable lives 'outside' the block in some sense, so these variables can be read and modified from code external to the block.

I've been brief, but you can find better explanations here, listed in increasing complexity:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值