Search code examples
objective-cobjective-c-blockscategories

Preventing a crash if a block is nil without thousands of ifs


I love using blocks. I constantly create custom classes that use blocks to communicate with callers instead of delegate mechanisms.

But the problem is that these classes got polluted with checks to see if the block was declared before running them. Something like:

if (self.onExit) {
  self.onExit(flag);
}

obviously I cannot omit the if or the code will crash if _onExit is nil;

Is there something I can create, a category or something, that will allow me to just run the block directly without the thousands of ifs but will internally check for nil before running it?


Solution

  • What about a macro like this?

    #define BLOCK_SAFE_RUN(block, ...) block ? block(__VA_ARGS__) : nil

    This is from another answer with more details here: https://stackoverflow.com/a/13037198/747339