views:

654

answers:

2

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.

+8  A: 
NSLog( @"%s" , _cmd );

_cmd is the SEL in any Objective-C method.

drawnonward
That's it? Wow.
Jacob Relkin
Really thanks for it:)
vodkhang
You really should use `NSLog(@"%@", NSStringFromSelector(_cmd))`, if you're going to use `_cmd`, since AFAIK Apple declares `_cmd` as type `SEL`, not a C-string. Just because it happens to be implemented as a C-string (as of the current versions of Mac OS X and the iPhone OS) doesn't mean you should use it in that way, since Apple could change it in an OS update.
Nick Forge
Yes, NSStringFromSelector is the more correct answer. I never use _cmd as c string for anything but debug code.
drawnonward
+13  A: 

To technically answer your question, you want:

NSLog(@"<%@:%@:%d>", NSStringFromClass([self class]), NSStringFromSelector(_cmd), __LINE__);

Or you could also do:

NSLog(@"%s", __PRETTY_FUNCTION__);
Dave DeLong
With `__FUNCTION__` and its pretty equivalent also being available in C-functions.
Georg Fritzsche
Thanks, it looks better and nicer than my current version
vodkhang
`__PRETTY_FUNCTION__` is the best option IMO. It's a totally readable representation of the current method or function.
Chuck