[英]How do I test for class type in Objective-C?
I'm trying to use -isKindOfClass:
to test for the class type but it doesn't work for me when I store the class type in a variable.我正在尝试使用
-isKindOfClass:
来测试类类型,但是当我将类类型存储在变量中时它对我不起作用。
Here is an example.这是一个例子。 What am I missing?
我错过了什么?
@interface MyClass : NSObject
@end
@implementation MyClass
@end
Class classType = [MyClass class];
[classType isKindOfClass:[MyClass class]]; // returns NO
classType == [MyClass class]; // returns YES
The problem is that MyClass does not inherit from MyClass.问题是 MyClass 没有从 MyClass 继承。
isKindOfClass
works the way you expect when you use it as an instance method:当您将
isKindOfClass
用作实例方法时,它会按照您期望的方式工作:
[[classType new] isKindOfClass:[MyClass class]]; // YES
But when you use it as a class method, it tests inheritance:但是当你将它用作类方法时,它会测试继承:
[classType isKindOfClass:[NSObject class]]; // YES
If you want to know whether classType
is [MyClass class]
, use ==
, exactly as you are doing.如果您想知道
classType
是否为[MyClass class]
,请使用==
,就像您正在做的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.