#、__VA_ARGS__

2020-07-22  本文已影响0人  tom__zhu

#

作用:将参数转换为字符串

例子1:

#define P(A) printf("%s:%d",#A,A)
@implementation MyClass
- (void)foo {
  int a = 1;
  P(a);
}
@end

输出:a:1

例子2:

#define P(x) print("the square of "#x" is %d", x*x)
@implementation MyClass
- (void)foo {
  P(2);
}
@end

输出:the square of 2 is 4


VA_ARGS

作用:可变参数宏(variadic macros)。用于宏定义中参数列表的最后一个参数为省略号,一般多用在调试信息。形如#define P(...) printf(__VA_ARGS__)
例子1:

#define NS_DEPRECATED(_macIntro, _macDep, _iosIntro, _iosDep, ...)\
CF_DEPRECATED(_macIntro, _macDep, _iosIntro, _iosDep, __VA_ARGS__)

例子2:函数中获取可变参数内容

#define Log(...) [LogHelper log:__VA_ARGS__]

@implementation LogHelper
- (void)log:(NSString *)fmt, ... {
    va_list args;
    if (fmt) {
        va_start(args, fmt);
        NSString *str = [[NSString alloc] initWithFormat:fmt arguments:args];
        va_end(args);
        NSLog(@"%@", str);
    }
}
@end
上一篇 下一篇

猜你喜欢

热点阅读