how to pass block as a macro's argument in objective-c?

白昼怎懂夜的黑 提交于 2019-12-01 16:22:24

问题


In my code i have a lot of code like:

if (block) block(....)

So I want to define a macro, something like

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

But i couldn't get it to work. Any idea?


回答1:


You don't need the ## and the ; needs moving:

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



回答2:


This can run into issues if your block is inline and contains code that has a series of comma separated strings, etc.

Example:

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

The compiler will complain about "Expected ']' or '.'" and "Expected identifier or '('".

However, if you were to 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);


来源:https://stackoverflow.com/questions/19109064/how-to-pass-block-as-a-macros-argument-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!