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

Objective CReflectionMetaprogrammingObjective C-Runtime

Objective C Problem Overview


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?

Objective C Solutions


Solution 1 - Objective C

NSString *name = NSStringFromClass ([NSArray class]);

You can even go back the other way:

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

Solution 2 - Objective C

Here's a different way to do it with slightly less typing:

NSString *name = [NSArray description];

Solution 3 - Objective C

Consider this alternative:

const char *name = class_getName(cls);

It's much faster, since it doesn't have to alloc NSString object and convert ASCII to whatever NSString representation is. That's how NSStringFromClass() is implemented.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlex WayneView Question on Stackoverflow
Solution 1 - Objective CdreamlaxView Answer on Stackoverflow
Solution 2 - Objective CSherwin ZadehView Answer on Stackoverflow
Solution 3 - Objective Cwonder.miceView Answer on Stackoverflow