SpaceDog SpaceDog - 11 months ago 56
Objective-C Question

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

obviously I cannot omit the
or the code will crash if

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

Answer Source

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: