views:

313

answers:

5

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?

+11  A: 

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);
Martin Gordon
You can also use the **`__PRETTY_FUNCTION__`** macro, which the preprocessor replaces with a C string (char*) of the method name. It also works for C functions.
Quinn Taylor
+1  A: 

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.

Adam Wright
There are times it is valid, though.
Abizern
+1  A: 

I don't know if this helps but, you can to do a search about what is the result of

@selector(myFooBarMethod:withFoo:bar:moreFoo:)

But, may I, ask why do you need the name of a method inside of it?

By the way: "selector" is another way of saying "method name".

nacho4d
A: 

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.

Abizern
+1  A: 

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:]".
Peter Hosey