So thanks to this post, I'm familiar with the __block keyword. It basically means to NOT copy the instance, but rather just passing its original reference.
The benefits I see for doing that are:
- Any modification made to the instance inside the block will reflect in the original instance.
- Avoiding the "waste" of copying the instance we're gonna use inside the block.
I am curious, though, how much should we really bother with this declaration, for example, if I have this method that receives a callback
block as a parameter:
-(void)doSomethingWithCallback:(MyTypeOfCallback)callback;
and let's say this method calls another method with a callback as a parameter. Is it then worthwhile to __block
the original callback
parameter if we want to call it inside the next method:
-(void)doSomethingWithCallback:(MyTypeOfCallback)callback
{
__block MyTypeOfCallback blockCallback = callback;
[self doAnotherThingWithBlock:^(BOOL result) {
if (result)
blockCallback();
}];
}
or should I simply call the original block
parameter inside the next method?
-(void)doSomethingWithCallback:(MyTypeOfCallback)callback
{
[self doAnotherThingWithBlock:^(BOOL result) {
if (result)
callback();
}];
}
I'm asking because it makes sense to include the __block option, but then again I find myself doing it in too many places and it's starting to take many code lines.
BTW, this also goes for every any other type of parameter, not only blocks.