开发者

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?


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

You can even go back the other way:

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


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

NSString *name = [NSArray description];


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜