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.
- possible duplicate of How do I print the type or class of a variable in Swift?Cihat Gündüz– Cihat Gündüz2014-12-18 16:31:42 +00:00Commented Dec 18, 2014 at 16:31
Add a comment |
4 Answers
NSStringFromClass
Returns the name of a class as a string.
NSString * NSStringFromClass ( Class aClass );
1 Comment
Efren
If ending up here from google and actually want the SWIFT 3 answer, use eg:
String(describing: MyViewController.self) : stackoverflow.com/a/34878224/1736679Use the function:
const char * class_getName(Class cls) as
class_getName ([vc class]); 3 Comments
xonegirlz
how do I cast from char* to NSString?
Duncan C
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().
Ephemera
class_getName() is the runtime function that NSStringFromClass would use under the hood.you can do some thing like the following when you instantiate your object:
[[NSClassFromString(@"className1") alloc] init]; 1 Comment
Harpastum
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).