Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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__.

You can use isMemberOfClass: which tells whether the given object is instance of that particular class or not.

You can get the current class name with NSStringFromClass(self.class) You can get the current method name using NSStringFromSelector(_cmd) (_cmd selector which is a hidden argument for each method).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top