Objective-C class -> string like: [NSArray className] -> @"NSArray"

Alex Wayne picture Alex Wayne · Feb 25, 2010 · Viewed 57.4k times · Source

I am trying to get a string name of a class from the class object itself.

// For instance
[NSArray className]; // @"NSArray"

I have found object_getClassName(id obj) but that requires an instance be passed to it, and in my case that is needless work.

So how can I get a string from a class object, and not an instance?

Answer

dreamlax picture dreamlax · Feb 25, 2010
NSString *name = NSStringFromClass ([NSArray class]);

You can even go back the other way:

Class arrayClass = NSClassFromString (name);
id anInstance = [[arrayClass alloc] init];