Alex Wayne
Alex Wayne

Reputation: 187034

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

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?

Upvotes: 131

Views: 61103

Answers (3)

wonder.mice
wonder.mice

Reputation: 7563

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.

Upvotes: 2

Sherwin Zadeh
Sherwin Zadeh

Reputation: 1452

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

NSString *name = [NSArray description];

Upvotes: 2

dreamlax
dreamlax

Reputation: 95335

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

You can even go back the other way:

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

Upvotes: 314

Related Questions