What exactly does the __block
keyword in Objective-C mean? I know it allows you to modify variables within blocks, but I'd like to know...
- What exactly does it tell the compiler?
- Does it do anything else?
- If that's all it does then why is it needed in the first place?
- Is it in the docs anywhere? (I can't find it).
It tells the compiler that any variable marked by it must be treated in a special way when it is used inside a block. Normally, variables and their contents that are also used in blocks are copied, thus any modification done to these variables don't show outside the block. When they are marked with
__block
, the modifications done inside the block are also visible outside of it.For an example and more info, see The __block Storage Type in Apple's Blocks Programming Topics.
The important example is this one:
In this example, both
localCounter
andlocalCharacter
are modified before the block is called. However, inside the block, only the modification tolocalCharacter
would be visible, thanks to the__block
keyword. Conversely, the block can modifylocalCharacter
and this modification is visible outside of the block.From the Block Language Spec:
For details on what a __block variable should compile to, see the Block Implementation Spec, section 2.3.
__block
is a storage type that is use to make in scope variables mutable, more frankly if you declare a variable with this specifier, its reference will pe passed to blocks not a read-only copy for more details see Blocks Programming in iOS@bbum covers blocks in depth in a blog post and touches on the __block storage type.
As for use cases you will find
__block
is sometimes used to avoid retain cycles since it does not retain the argument. A common example is using self.hope this will help you
let suppose we have a code like:
it will give an error like "variable is not assignable" because the stack variable inside the block are by default immutable.
adding __block(storage modifier) ahead of it declaration make it mutable inside the block i.e
__block int stackVariable=1;
It means that the variable it is a prefix to is available to be used within a block.