I’ve seen a lot of source code recently where people are mis-using the __block
“specifier” that ships with modern Objective-C runtimes. I’ve always had the opinion that if you are to use __block for an Object then you should design around it and avoid, reserving its use for primitives. Regardless of that, here is a summary of my understanding of __block to share with any other keen readers who may be interested.
__block
is used as variables outside the scope of a block become readonly once inside a block. For example
int num=1;
void (^someBlock)(void) = ^{
num = 2;
};
someBlock();
Would cause a compiler error asking for the __block specifier to be used. so in this case you can try:
__block int num=1;
void (^someBlock)(void) = ^{
num = 2;
};
someBlock();
and num
will contain the correct value after block execution.
Straight forward right? So what about the following example:
__block NSMutableArray *someArray = @[@"Hello",@"World"];
void (^someBlock)(void) = ^{
[someArray addObject:@"Goodbye"];
};
someBlock();
It’s wrong… you don’t need __block
in this case… why? because you’re not assigning a value to the captured “variable” someArray
, rather you’re just sending a message. I often see this and wonder why.
The __block
specifier is actually a storage-class specifier, to give you an idea of what this means, the following are also storage-class specifiers in C. extern, typedef, static
and so on.
Why don’t I like __block
a great deal then? Read on for more…
… →