james_womack
james_womack

Reputation: 10296

Objective C: Method have knowledge of context within which it was called?

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"
    }

Upvotes: 1

Views: 152

Answers (2)

james_womack
james_womack

Reputation: 10296

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

Upvotes: 0

Chuck
Chuck

Reputation: 237010

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.

Upvotes: 2

Related Questions