objective-c 从实例中获取类的名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2217560/
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 22:53:59  来源:igfitidea点击:

Getting name of the class from an instance

iphoneobjective-cclassinstanceclassname

提问by Robin

I have the following problem: I get an instance of a class passed and want to know the name of the class of this instance. How to get this?

我有以下问题:我得到一个类的实例,想知道这个实例的类的名称。如何得到这个?

回答by CiNN

NSStringFromClass([instance class])should do the trick.

NSStringFromClass([instance class])应该做的伎俩。

回答by kubi

if all you want to do is test an object to see if it's a type of a certain Class

如果你想做的只是测试一个对象,看看它是否是某个类的类型

BOOL test = [self isKindOfClass:[SomeClass class]];

回答by Katedral Pillon

From within the class itself

从类本身内部

-(NSString *) className
{
    return NSStringFromClass([self class]);
}

回答by ealee

Just add a category:

只需添加一个类别:

NSObject+Extensions.h
- (NSString *)className;

NSObject+Extensions.m
- (NSString *)className {
    return NSStringFromClass(self.class);
}

Then use the following code:

然后使用以下代码:

NSString *className = [[SomeObject new] className];

or even:

甚至:

NSString *className = SomeObject.new.className;

To use it anywhere add the category to YourProject.pch file.

要在任何地方使用它,请将类别添加到 YourProject.pch 文件中。

回答by Lal Krishna

OBJC:

对象:

NSStringFromClass([instance class])

SWIFT

迅速

From instance:

从实例:

String(describing: YourType.self)

From type:

从类型:

String(describing: self)

回答by Jeremie D

You can also use [[self class] description]

你也可以使用 [[self class] description]

回答by Roman Barzyczak

If you are looking how get classname in Swift you can use reflect to get information about object.

如果您正在寻找如何在 Swift 中获取类名,您可以使用反射来获取有关对象的信息。

let tokens = split(reflect(self).summary, { ##代码## == "." })
if let typeName = tokens.last {
    println(typeName)
}