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);

Jayesh Kawli

I am a web and mobile developer working at Wayfair in Boston, MA. I come to learn so many things during course of life and I write about things which helped me and feel like they can help others too.

Subscribe to Fresh Beginning

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!