How to pass a block as a macro argument to objective-c?

In my code I have a lot of code:

if (block) block(....) 

So I want to define a macro, something like

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

But I could not get it to work. Any idea?

+6
source share
2 answers

You do not need moves ## and ; :

 #define safetyCall(block, ...) if((block)) { block(__VA_ARGS__); } 
+6
source

This can lead to problems if your block is inline and contains code that contains a series of comma separated lines, etc.

Example:

 safetyCall(^void() { NSArray *foo = @[@"alice", "bob"]; }; 

The compiler will complain about "Expected") or "." and "Expected Identifier" or "(.).

However, if you must declare the inline block as a separate block before the macro, it will not generate an error.

Example:

 void (^fooBlock)(void) = ^void() { NSArray *foo = @[@"alice", @"bob"]; } safetyCall(fooBlock); 
+2
source

Source: https://habr.com/ru/post/954992/


All Articles