Any way to ask a method for its name?

你离开我真会死。 提交于 2020-01-12 03:16:06

问题


I'm trying to debug an iPhone app I'm working on, and the idea of adding fifty NSLog statements to the various source files gives me the willies.

What I'd like to do is write a pair of statements, say

NSString *methodName = [self methodName];
NSLog(@"%@", methodName);

that I can just paste into each method I need to. Is there a way to do this? Is there some Objective-C construct for asking a method for its name? Or am I gonna have to do this the hard way?


回答1:


Try NSLog(@"%s", __func__). This prints out a pretty description, like -[MyView drawRect:].

This also works with functions. It's a compiler feature.




回答2:


Use: NSLog("%@", NSStringFromSelector(_cmd));

_cmd is a special variable passed to every method just like self which is a reference to the selector that caused the method to be invoked (basically the method's name and signature).




回答3:


I use the following macros frequently:

#if DEBUG
#  define LOG(format, args ...) fprintf(stderr, format "\n", ## args)
#  ifdef __cplusplus
#    define ERR(format, args ...) fprintf(stderr, "[%s] (%s:%i): " format "\n", __PRETTY_FUNCTION__, __FILE__, __LINE__, ## args)
#  else
#    define ERR(format, args ...) fprintf(stderr, "[%s] (%s:%i): " format "\n", __func__, __FILE__, __LINE__, ## args)
#  endif
#else
#  define LOG(format, args ...)
#  define ERR(format, args ...)
#endif

If you always wanted the function name you could easily adapt them as required.




回答4:


This is what you want:

NSLog(@"%s", __PRETTY_FUNCTION__);

For more info on related logging stuff, read over the answers to this question: How to print out the method name and line number and conditionally disable NSLog?



来源:https://stackoverflow.com/questions/2687785/any-way-to-ask-a-method-for-its-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!