Objective-C 类 -> 字符串如:[NSArray className] -> @"NSArray"

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2331983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 23:08:36  来源:igfitidea点击:

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

objective-creflectionmetaprogrammingobjective-c-runtime

提问by Alex Wayne

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.

我发现object_getClassName(id obj)但这需要一个实例传递给它,在我的情况下这是不必要的工作。

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

那么如何从类对象而不是实例中获取字符串呢?

回答by dreamlax

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

You can even go back the other way:

你甚至可以用另一种方式返回:

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

回答by Sherwin Zadeh

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

这是一种不同的方法,可以稍微减少输入:

NSString *name = [NSArray description];

回答by wonder.mice

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 NSStringrepresentation is. That's how NSStringFromClass()is implemented.

它要快得多,因为它不必分配 NSString 对象并将 ASCII 转换为任何NSString表示形式。就是这样NSStringFromClass()实现的。