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

心已入冬 提交于 2019-11-26 23:48:42

问题


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?


回答1:


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

You can even go back the other way:

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



回答2:


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

NSString *name = [NSArray description];



回答3:


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.



来源:https://stackoverflow.com/questions/2331983/objective-c-class-string-like-nsarray-classname-nsarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!