NSLog the method name with Objective-C in iPhone

vodkhang picture vodkhang · May 5, 2010 · Viewed 58.7k times · Source

Currently, we are defining ourselves an extended log mechanism to print out the class name and the source line number of the log.

#define NCLog(s, ...) NSLog(@"<%@:%d> %@", [[NSString stringWithUTF8String:__FILE__] lastPathComponent], \
    __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__])

For example, when I call NCLog(@"Hello world"); The output will be:

<ApplicationDelegate:10>Hello world

Now I also want to log out the method name like:

<ApplicationDelegate:applicationDidFinishLaunching:10>Hello world

So, this would make our debugging become easier when we can know which method is getting called. I know that we also have Xcode debugger but sometimes, I also want to do debugging by logging out.

Answer

drawnonward picture drawnonward · May 5, 2010
print(__FUNCTION__) // Swift
NSLog(@"%@", NSStringFromSelector(_cmd)); // Objective-C

Swift 3 and above

print(#function)