【发布时间】:2016-04-27 19:56:11
【问题描述】:
我有这样的事情:
static NSString * const MyLogPrefixFormat = @"%@ - %@";
static NSString * const MyDefaultLogPrefix = @"MyApp";
#define MyLogSetPrefix(newPrefix) ; static NSString * const MyLogPrefix = newPrefix;
#define MyLogManualPrefix(messagePrefix, logMessage, args...) NSLog([NSString stringWithFormat:MyLogPrefixFormat, messagePrefix, logMessage], ##args);
#define MyLog(logMessage, args...) MyLogManualPrefix(MyLogPrefix, logMessage, ##args);
- (void)myMethod
{
MyLogSetPrefix(@"myMethod");
MyLog(@"Message One with args 1 (%@) and 2 (%@)", arg1, arg2);
MyLog(@"Message Two");
}
扩展至此:
- (void)myMethod
{
static NSString * const MyLogPrefix = @"myMethod";
NSLog([NSString stringWithFormat:@"%@ - %@", MyLogPrefix, @"Message One with args 1 (%@) and 2 (%@)"], arg1, arg2);
NSLog([NSString stringWithFormat:@"%@ - %@", MyLogPrefix, @"Message Two"]);
}
但是,我也希望它这样做:
- (void)myMethod
{
MyLog(@"Message One", arg1, arg2);
MyLog(@"Message Two");
}
扩展至此:
- (void)myMethod
{
NSLog([NSString stringWithFormat:@"%@ - %@", MyDefaultLogPrefix, @"Message One with args 1 (%@) and 2 (%@)"], arg1, arg2);
NSLog([NSString stringWithFormat:@"%@ - %@", MyDefaultLogPrefix, @"Message Two"]);
}
要实现第二个要求,我需要检查是否设置了 MyLogPrefix 常量。因为它是static NSString * const 而不是#define,所以我不能使用#ifdef。 如何判断MyLogPrefix 常量是否存在,如果不存在,使用MyDefaultLogPrefix?
【问题讨论】:
标签: objective-c c-preprocessor