Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the name or signature of the current method into an NSString?

Every method call also passes two hidden arguments: an id named self and a SEL named _cmd. You can use NSStringFromSelector to convert the method selector to an NSString:

NSStringFromSelector(_cmd);

Use __func__. This is a C string, so for an NSString, use [NSString stringWithUTF8String:__func__].

This has two advantages over _cmd:

  1. It works in C functions and C++ methods as well as Objective-C methods. (In fact, __func__ is required to exist by C99.)
  2. In Objective-C methods, it includes the method type (class method vs. instance method) and the class name as well as the selector. For example, "-[MyView drawRect:]".

As an example of where this sort of thing is useful: This is a template for NSLog messages that I use:

NSLog(@"%@ %@: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), @"A Message");

This dumps the class and the method to the console when logging.


As per Martin's answer, but you might also like to read the Objective C 2.0 Runtime information.

Playing in the guts like this tends to lead to hard to manage code, however.