Macro for checking nil/NULL blocks

This is an easy and quick tip I came across while going through NSHipster's Reader Submissions - 2016. Sometimes we use the blocks which we may or may not be nil. Well, unlike other mechanism by which you can send message to nil object, you cannot call a nil/NULL block. It will result in the instant crash.

This NSHipster reader submission provides a macro which can be reused to automatically check for nil blocks.


#define BLOCK_EXEC(block, ...)  if (block) { block(__VA_ARGS__); };

So as Article points out, it replaces old and clunky way to check for nil blocks as follows,


if (block) {
    block(arg1, arg2);
}

Now instead of doing it, you can simply call it as,


BLOCK_EXEC(completionBlock, arg1, arg2);