NSLog macro that can take only one argument

185 views Asked by At
#define LogMsg(msg) ((DebugMode)?NSLog(@"<%@:%@:%d:%@>", NSStringFromClass([self class]), NSStringFromSelector(_cmd), __LINE__,msg):NO)

With this macro I can print out:

LogMsg(@"Test");

Or

NSArray *testArray = @[@"one",@"two"];
LogMsg(testArray);

How can I do the same with a macro replacement that will also take two arguments like NSLog and still be able to print the array in the form I'm doing with the above? example:

NSLog (@"test: %@",test);

  • I'd prefer not using a 3rd party Class for that and solve the above with a macro.
2

There are 2 answers

0
godel9 On

So close! Your macro works with the following invocations:

ALog("Test");
NSArray *testArray = @[@"one",@"two"];
ALog("%@", testArray);

The compiler will automatically concatenate:

@"%s [Line %d] " "Test"

to:

@"%s [Line %d] Test"
5
Martin R On

This should work:

#define LogMsg(msg, ...) ((DebugMode)?NSLog(@"<%@:%@:%d>" msg, NSStringFromClass([self class]), NSStringFromSelector(_cmd), __LINE__, ##__VA_ARGS__):NO)

It uses preprocessor string concatenation @"<%@:%@:%d>" msg to get a "combined format string" with the fixed and the variable part, and preprocessor variadic macros with ##__VA_ARGS__.

Added: I don't think that is possible to define a macro such that both

LogMsg(someObject);
LogMsg(formatString, arg1, arg2, ...);

work.