Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Objective C how can I get the class name of self at run time? [duplicate]

In Objective C 'self' is an instantiation of some class. How can I find out what class it's an instantiation of? IOW I want an NSString containing the name of the class. I know about isKindOfClass but that only tests whether it's a particular class whose name I have to know in advance. If I have 20 classes in my app (or 50) I'd have to write out 20 isKindOfClass statements to find out which class it is, and I'd have to rewrite them to do the same test in a different app. Isn't there a more direct way of getting the class name?

Also, how can I get an NSString containing the name of the method I'm in at run time?

I'd like to use these functions in a run time debugging method.

This question refers to Objective C and iOS.

like image 877
RobertL Avatar asked Dec 06 '22 04:12

RobertL


2 Answers

For the class:

NSStringFromClass([self class]);

For methods (assuming you are in the method you are interested in):

NSStringFromSelector(_cmd);

Side note, _cmd is passed just like self to every method in Objective C and is a SEL (selector) for the method you are in.

like image 68
Lance Avatar answered Jan 18 '23 17:01

Lance


Another option is this:

NSLog(@"%s", __PRETTY_FUNCTION__);

It's long but once you've used it a few times typing _tab will autocomplete to __PRETTY_FUNCTION__.

like image 43
Abhi Beckert Avatar answered Jan 18 '23 18:01

Abhi Beckert