27

If I have a UIViewController subclass, how can I get the class name as string? I've tried doing [vc class], but this returns a Class object, not an NSString.

1

4 Answers 4

49

NSStringFromClass

Returns the name of a class as a string.

NSString * NSStringFromClass ( Class aClass ); 
Sign up to request clarification or add additional context in comments.

1 Comment

If ending up here from google and actually want the SWIFT 3 answer, use eg: String(describing: MyViewController.self) : stackoverflow.com/a/34878224/1736679
20

You can do something like this

NSString *strClass = NSStringFromClass([viewController class]); 

Comments

4

Use the function:

const char * class_getName(Class cls) 

as

class_getName ([vc class]); 

3 Comments

how do I cast from char* to NSString?
you don't cast from char* to NSString. You have to create a string from bytes using a call like initWithBytes:length:encoding:. You'd probably use use the encoding NSASCIIStringEncoding. See the other poster's message about NSStringFromClass. That's much easier to use than the Objective C runtime function class_getName().
class_getName() is the runtime function that NSStringFromClass would use under the hood.
4

you can do some thing like the following when you instantiate your object:

[[NSClassFromString(@"className1") alloc] init]; 

1 Comment

xonegirlz asked how to get an NSString from a class, and your answer gets an instance of a class from an NSString (i.e. you gave the reverse of the answer).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.