从实例中获取类的名称
我有以下问题:我得到一个传递的类的实例,并且想知道该实例的类的名称。如何得到这个?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
NSStringFromClass([instance class])
应该可以解决问题。NSStringFromClass([instance class])
should do the trick.如果您只想测试一个对象以查看它是否是某个类的类型
if all you want to do is test an object to see if it's a type of a certain Class
从班级本身
From within the class itself
OBJC:
SWIFT
来自实例:
来自类型:
OBJC:
SWIFT
From instance:
From type:
您还可以使用
[[self class]描述]
You can also use
[[self class] description]
只需添加一个类别:
然后使用以下代码:
甚至:
要在任何地方使用它,请将类别添加到 YourProject.pch 文件中。
Just add a category:
Then use the following code:
or even:
To use it anywhere add the category to YourProject.pch file.
如果您正在寻找如何在 Swift 中获取类名,您可以使用 Reflect 来获取有关对象的信息。
If you are looking how get classname in Swift you can use reflect to get information about object.
NSString* classNameNSStr = [someObjcInstance className]
NSString* classNameNSStr = NSStringFromClass(someObjcClass)
const char* className = object_getClassName(someObjcClass)
-->;相关:
isKindOfClass
:BOOL isSameClass = [someObjcInstance isKindOfClass: SomeClass];
SomeClass
可以从以下位置获取:objc_getClass("SomeClassName")
NSString* classNameNSStr = [someObjcInstance className]
NSString* classNameNSStr = NSStringFromClass(someObjcClass)
const char* className = object_getClassName(someObjcClass)
--> related:
isKindOfClass
:BOOL isSameClass = [someObjcInstance isKindOfClass: SomeClass];
SomeClass
can get from:objc_getClass("SomeClassName")