Search code examples
objective-cmacrosnsthreadnslog

NSLog macro to print out if it is on the main thread


My current DEB_LOG macro extends NSLog to also print out the object, method, and line where it is being logged:

#define DEB_LOG(__FORMAT__,...) NSLog((@"%s line %d $ " __FORMAT__), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)

I would also like to expand it to report if it is on the main thread, if possible.

[NSThread isMainThread]

Is that possible?


Solution

  • This should do it:

    #define DEB_LOG(__FORMAT__,...) NSLog((@"%s line %d%s $ " __FORMAT__), \
        __PRETTY_FUNCTION__, __LINE__, \
        ([NSThread isMainThread] ? " (main thread)" : ""), \
        ##__VA_ARGS__)
    

    The output generated from

    DEB_LOG(@"%@", @"Hello world");
    

    is

    -[AppDelegate application:didFinishLaunchingWithOptions:] line 20 (main thread) $ Hello world