Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
like image 617
aryaxt Avatar asked Dec 13 '12 21:12

aryaxt


People also ask

Can I call function in C through macro?

The Concept of C Macros Macros can even accept arguments and such macros are known as function-like macros. It can be useful if tokens are concatenated into code to simplify some complex declarations. Macros provide text replacement functionality at pre-processing time. The above macro (MAX_SIZE) has a value of 10.

Can we call a function from macro?

Just type the word Call then space, then type the name of the macro to be called (run). The example below shows how to call Macro2 from Macro1. It's important to note that the two macros DO NOT run at the same time. Once the Call line is hit, Macro2 will be run completely to the end.

How do you call a function in a macro?

You can expand the ... of variadic macros with __VA_ARGS__ . Note: As you probably know, the parentheses prevent the function argument from being expanded as a macro (if it is a macro). I.e., #define BAR(...) myprintf(__VA_ARGS__) MACROFOO(BAR, "hello world%c", '!


1 Answers

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];
}
like image 173
Sergey Kalinichenko Avatar answered Jan 19 '23 10:01

Sergey Kalinichenko