17

I'd like to be able to put trace messages of the current class name and method name for all classes in my project.

Is there a way to get the current method's name at run time, similar to:

NSLog(@"classname: %@", [self className]);

where self is a class derived out of NSObject?

Alexi Groove
  • 6,646
  • 12
  • 47
  • 54

3 Answers3

35
NSLog(@"method name: %@", NSStringFromSelector(_cmd));

_cmd is a hidden argument (like self) that all Objective-C methods receive. Its value is the selector that was used to call the method.

Chuck
  • 234,037
  • 30
  • 302
  • 389
18

EDITED: i think this method is more generic...check it out..

NSLog(@"%s", __PRETTY_FUNCTION__);
Nishant
  • 12,529
  • 9
  • 59
  • 94
  • my apologies if i come out as condescending, didnt mean to... I found this solution to be more generic... – Nishant Jul 16 '12 at 06:23
  • 2
    great answer. i put it into a macro, like this: #define LOGME NSLog(@"%s", \_\_PRETTY_FUNCTION\_\_); – Ben H May 06 '13 at 21:36
  • Great Answer @Nishant .. It is giving both the class name and the method name for good debugging... – Ashok Dec 06 '13 at 06:40
  • great,this macro help me a lot,it give more comprehensive information about current class and method to be called – inix Apr 18 '15 at 13:34
  • Nice trick but it provides not only the method's name but also the class name it belongs to which is not really what Alexi Groove initially wanted. The solution of Chuck including '_cmd' is the best one in my view. – XLE_22 Apr 19 '17 at 11:43
1

This also works:

NSLog(@"%@", [NSString stringWithUTF8String:__func__])
hrchen
  • 1,223
  • 13
  • 17