繁体   English   中英

预处理程序可以将Objective-C宏扩展到多行吗?

[英]Can the preprocessor expand Objective-C macros to multiple lines?

具有此宏:

#define RUN_ON_MAIN_THREAD(block) dispatch_async(dispatch_get_main_queue(), block)

以及它的用法:

RUN_ON_MAIN_THREAD(^{
    NSLog(@"first line");

    NSLog(@"second line");
});

它扩展为:

dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"first line"); NSLog(@"seconds line"); });

这使得在NSLog(@"second line");的行上不可能有一个工作断点NSLog(@"second line");

有什么办法可以使其扩展为:

dispatch_async(dispatch_get_main_queue(), ^{
    NSLog(@"first line");

    NSLog(@"seconds line");
});

是的,您可以定义多行宏(在行的末尾使用\\ ),并且宏可以扩展为多行(尽管在技术上是不必要的,因为C / Obj-C会忽略大多数空白)。

但是真正的答案是:不要这样做

此全局函数将(a)生成与您的宏等效的源代码,并且(b)实际上将生成较少的机器代码。 (您的宏反复生成相同的调度调用,而此函数将它们封装在一个代码块中。)

// Shorthand for asynchronously dispatching a block to execute on the main thread
void DispatchOnMain( dispatch_block_t block )
{
    dispatch_async(dispatch_get_main_queue(),block);
}

您的代码将如下所示:

DispatchOnMain(^{
    NSLog(@"first line");

    NSLog(@"second line");
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM