目标C-定义宏以调用方法吗? [英] Objective C - Defining macro to call a method?
问题描述
我想定义一个宏来调用以下内容,这可能吗? 我也希望它接受格式字符串.
I want to define a macro to call the following, Is this possible? I also want it to accept format string.
- (void)logString:(NSString *)string withLogLogLevel:(LogLevel)logLevel
{
// Sav log to file
}
DLog("text");
[Logger logString:text withLogLevel:LogLevelDebug];
ILog("text");
[Logger logString:text withLogLevel:LogLevelInfo];
ELog("text");
[Logger logString:text withLogLevel:LogLevelInfo];
推荐答案
假定logString:withLogLevel:
除了日志级别外还采用单个字符串参数,这应该是可能的:
Assuming that logString:withLogLevel:
takes a single string parameter in addition to the log level, this should be possible:
#define DLog(x) [Logger logString:(x) withLogLevel:LogLevelDebug]
请注意macro参数周围的括号,当用复合表达式调用宏时,此功能很有用.
Note the parentheses around the macro parameter, it is useful when macros are called with composite expressions.
假设记录器使用的是NSString
对象,而不是C字符串,则应使用这样的宏:
Assuming that the logger takes NSString
objects, not C string, you should use the macro like this:
DLog(@"Text");
DLog(@"Text");
但是,在这种情况下,尚不清楚为什么人们会偏爱宏而不是简单的函数调用:
However, in this case it is not clear why would one prefer a macro to a simple function call:
void DLog(NSString *str) {
[Logger logString:str withLogLevel:LogLevelDebug];
}
这篇关于目标C-定义宏以调用方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!