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
.
Asked
Active
Viewed 2.3k times
27
-
possible duplicate of [How do I print the type or class of a variable in Swift?](http://stackoverflow.com/questions/24006165/how-do-i-print-the-type-or-class-of-a-variable-in-swift) – Jeehut Dec 18 '14 at 16:31
4 Answers
49
NSStringFromClass
Returns the name of a class as a string.
NSString * NSStringFromClass ( Class aClass );
-
If ending up here from google and actually want the SWIFT 3 answer, use eg: `String(describing: MyViewController.self)` : https://stackoverflow.com/a/34878224/1736679 – Efren May 29 '17 at 03:35
20
You can do something like this
NSString *strClass = NSStringFromClass([viewController class]);

Vaibhav Saran
- 12,848
- 3
- 65
- 75

Hardik Darji
- 3,633
- 1
- 30
- 30
4
Use the function:
const char * class_getName(Class cls)
as
class_getName ([vc class]);

GoZoner
- 67,920
- 20
- 95
- 145
-
-
1you 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(). – Duncan C Jun 05 '12 at 00:19
-
`class_getName()` is the runtime function that NSStringFromClass would use under the hood. – Ephemera Dec 18 '14 at 00:14
4
you can do some thing like the following when you instantiate your object:
[[NSClassFromString(@"className1") alloc] init];

shebelaw
- 3,992
- 6
- 35
- 48
-
4xonegirlz 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). – Harpastum Mar 14 '13 at 16:45