Getting name of the class from an instance

删除回忆录丶 提交于 2019-12-03 01:23:36

问题


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?


回答1:


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




回答2:


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]];



回答3:


From within the class itself

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



回答4:


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.




回答5:


You can also use [[self class] description]




回答6:


OBJC:

NSStringFromClass([instance class])

SWIFT

From instance:

String(describing: YourType.self)

From type:

String(describing: self)



回答7:


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

let tokens = split(reflect(self).summary, { $0 == "." })
if let typeName = tokens.last {
    println(typeName)
}


来源:https://stackoverflow.com/questions/2217560/getting-name-of-the-class-from-an-instance

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