Getting name of the class from an instance

2019-03-08 02:41发布

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?

7条回答
趁早两清
2楼-- · 2019-03-08 03:03

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楼-- · 2019-03-08 03:04

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

查看更多
一夜七次
4楼-- · 2019-03-08 03:12

From within the class itself

-(NSString *) className
{
    return NSStringFromClass([self class]);
}
查看更多
虎瘦雄心在
5楼-- · 2019-03-08 03:12

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.

查看更多
Explosion°爆炸
6楼-- · 2019-03-08 03:27

OBJC:

NSStringFromClass([instance class])

SWIFT

From instance:

String(describing: YourType.self)

From type:

String(describing: self)
查看更多
在下西门庆
7楼-- · 2019-03-08 03:28

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)
}
查看更多
登录 后发表回答