Question

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

Example: I have a method -myFooBarMethod:withFoo:bar:moreFoo: and inside the implementation of that method I want to dynamically get the name of it, like @"-myFooBarMethod:withFoo:bar:moreFoo: into an NSString. No hard-typing of the method signature.

I feel that this has to do something with selectors. How could I get the name of the current method (the one that executes the code) as NSString?

 45  12545  45
1 Jan 1970

Solution

 98

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);
2009-09-03

Solution

 17

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:]".
2009-09-03