Question

I'd like to have a reusable logging method or function that spits out the name of the method it's called from. Example:

    - (void)exampleMethod {
        CustomLog(); //Outputs "exampleMethod"
    }
Was it helpful?

Solution

Functions don't know about their calling environment (at least not in a useful way). The only way is to use a macro instead. Inside the macro, you have access to the self and _cmd arguments that hold the receiver and current selector, as well as the __PRETTY_FUNCTION__ macro that contains the human-readable name of the method as a C string.

OTHER TIPS

See How to print out the method name and line number and conditionally disable NSLog? for the inspiration for this answer and other useful NSLog tips. Here is what I desired:

//place in PCH file
#define ILog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);

//use in any file in your project
ILog(@"test");// outputs -[AppDelegate applicationDidFinishLaunching:] [Line 38] test
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top