1

I'm working on an API which includes a lot of block arguments with its interface. I decided the library should accept nil for block arguments. So it is necessary to check for nil before calling any block in the implementation.

However, the code would become quite ugly if there is a lot of if.

if (completionHandler) {
    completionHandler(userInfo, success, error)
}

one line of code would become 3 lines.

I'm currently using such a macro definition to avoid this,

#define completionHandler(...) if (completionHandler) completionHandler(__VA_ARGS__)

It works well. But this technique limits the name of my callbacks to "completionHandler". Is there an more elegant and also safe way to support arbitrary callback names?

Does any one have any suggestions on nil checking?

Zili FENG
  • 191
  • 11
  • Does this help at all? http://stackoverflow.com/questions/21054024/which-is-the-best-way-to-check-method-arguments-in-objective-c – lostintranslation Jul 27 '15 at 03:45
  • You can make the block name the first parameter of the macro: `#define iff(completionHandler, ...) if (completionHandler) completionHandler(__VA_ARGS__)` and then `iff(completionHandler, success, error);` – Rob Jul 27 '15 at 03:50

1 Answers1

0

One option which does it in one line and completely abuses operators is:

completionHandler && ( completionHandler(userInfo,success,error) , YES )

I'd recommend steering clear of using macros for that. Generally, macros can improve readability, except that you are adding what look like primitives to the vocabulary of your application and confuses things.

You also don't have to put the { }:

if (completionHandler) completionHandler(userInfo,success,error) ;
iAdjunct
  • 2,739
  • 1
  • 18
  • 27
  • I agree with iAdjunct. In your case, using a macro will cut down on the readability of your code and make debugging a pain. Honestly, in my opinion the three line solution you are trying to minimize is the clearest and most readable way of handling calling a block. – duncanc4 Jul 27 '15 at 04:02