aryaxt
aryaxt

Reputation: 77596

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];

Upvotes: 11

Views: 9089

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

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]

Note the parentheses around the macro parameter, it is useful when macros are called with composite expressions.

Assuming that the logger takes NSString objects, not C string, you should use the macro like this:

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];
}

Upvotes: 10

Related Questions