如何在目标c中获取类名,例如“ NSString” [英] How to get classname in objective c Like 'NSString'

查看:61
本文介绍了如何在目标c中获取类名,例如“ NSString”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取我们正在使用的对象的类名。
这意味着现在如果我编写这段代码

I want to get the class name of an object as what we are using. That means now if I write this code

 NSString *s = [NSString string];
 NSLog(@"%@",[s class]);

输出为 __ NSCFConstantString

我如何将其作为 NSString 本身获得?

How can I get it as NSString itself ?

注意: NSString 只是一个例子

我知道 __ NSCFConstantString 是正确。但是我的意图是得到 NSString

I know __NSCFConstantString is correct. But my intention is to get like NSString. Is there any way to acheive this?

推荐答案

尝试一下,它们将输出 NSString 。请记住,第二组需要导入Objective-C运行时标头。

Give these a try, they'll output NSString. Keep in mind, the second set requires importing the Objective-C runtime header.

#import <objc/runtime.h>

NSString *string = @"I'm a string.";


NSLog(@"%@",NSStringFromClass([string classForCoder]));
NSLog(@"%@",NSStringFromClass([string classForKeyedArchiver]));

NSLog(@"%s",class_getName([string classForCoder]));
NSLog(@"%s",class_getName([string classForKeyedArchiver]));

现在,这并非在所有情况下都有效。例如,尝试以这种方式获取 NSConstantString 的类,将输出 NSString 。如果您需要以这种方式将类名检查为字符串,则可能应该重新考虑解决问题的方法。

Now, this won't work in all cases. For example, trying to get the class of NSConstantString, in this manner will output NSString. If you require checking the class name as a string in this way, you probably should reconsider your approach to solving the problem.

这篇关于如何在目标c中获取类名,例如“ NSString”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆