4 ms·
That's cool, but it's actually possible to use recursive blocks directly if you simply declare the block as a __block variable. This works perfectly fine: __
by schrototo 16y ago
That's cool, but it's actually possible to use recursive blocks directly if you simply declare the block as a __block variable. This works perfectly fine:
__block void (^myBlock);
myBlock = ^{ myBlock(); };
myBlock();
The only thing you have to watch out for is when the block gets copied prior to its invocation (e.g. if you pass it to some function that does a Block_copy on it). In that case you have to first copy the block yourself and update your block variable:
__block void (^myBlock);
myBlock = [^{ myBlock(); } copy];
someFunctionThatCopiesTheBlock(myBlock);
- jballanc 16y agoHeh, I was wondering when someone would bring this up. For most cases, this also works. I will say that I've seen cases where this technique hasn't worked, but those were all far, far more complex than most any Obj-C programmer will ever need to worry about.