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?
我遇到了以下问题:我获得一个传递的类的实例,并希望知道这个实例的类的名称。这个怎么走吗?
6 个解决方案
#1
343
NSStringFromClass([instance class])
should do the trick.
NSStringFromClass([实例类])应该执行这个技巧。
#2
26
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
16
From within the class itself
来自类本身
-(NSString *) className
{
return NSStringFromClass([self class]);
}
#4
2
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.
要在任何地方使用它,请将类别添加到项目中。pch文件。
#5
1
You can also use [[self class] description]
你也可以使用[[self class] description]
#6
0
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, { $0 == "." })
if let typeName = tokens.last {
println(typeName)
}
#1
343
NSStringFromClass([instance class])
should do the trick.
NSStringFromClass([实例类])应该执行这个技巧。
#2
26
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
16
From within the class itself
来自类本身
-(NSString *) className
{
return NSStringFromClass([self class]);
}
#4
2
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.
要在任何地方使用它,请将类别添加到项目中。pch文件。
#5
1
You can also use [[self class] description]
你也可以使用[[self class] description]
#6
0
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, { $0 == "." })
if let typeName = tokens.last {
println(typeName)
}