目标C - #define使用__VA_ARGS__

Cla*_*lad 1 objective-c variadic-functions ios c-preprocessor variadic-macros

我正在学习如何使用宏但现在与一个混淆.

我正在尝试创建一个NSString将每个params彼此附加的连接.

例如:concatOP(@"hey",@"Jude",@"Don't")将返回一个NSString包含:@"heyJudeDon't"

我实际上做了一些代码(这里也有一些代码)可以得到params的数量,但是我没有成功完成工作的第二部分.

#define NUMARGS(...)        ( sizeof((int[]){__VA_ARGS__}) / sizeof(int) )
#define concatOP(...)       NSMutableString *format = [[NSMutableString alloc] init];\
                            for( int i = 0; i < NUMARGS(__VA_ARGS__); i++){\
                            [format appendString:@"%@"];}\
                            [[NSString alloc] initWithFormat:format, __VA_ARGS__]
Run Code Online (Sandbox Code Playgroud)

我实际上遇到了很多错误,告诉我格式不存在或者我错过了一些";" 或其他结束标签.

Cy-*_*4AH 7

这是你的宏:

#define concatOP(...) [@[__VA_ARGS__] componentsJoinedByString:@""]
Run Code Online (Sandbox Code Playgroud)

编辑:如果你解开你的宏,NSString* result = concatOP(@"hey",@"Jude",@"Don't"); 你会得到:

NSString* result = NSMutableString *format = [[NSMutableString alloc] init]; for( int i = 0; i < NUMARGS(@"hey",@"Jude",@"Don't"); i++){ format = [format appendString:@"%@"];} [[NSString alloc] initWithFormat:format, @"hey",@"Jude",@"Don't"];
Run Code Online (Sandbox Code Playgroud)

看起来很奇怪