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

二次信任 提交于 2019-12-01 17:09:21

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

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

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