This is most easily explained with a brief example. Let's say I have the following protocol and class definitions:
这很容易用一个简单的例子来解释。假设我有以下协议和类定义:
@protocol ProtocolA <NSObject>
@optional
+ (BOOL)methodA;
@end
@interface ClassA : NSObject <ProtocolA>
@end
ClassA
may or may not define methodA
. If I was working with an instance of ClassA
and an instance method, I could test the instance with respondsToSelector:
. In this situation, however, I cannot think of any clean way to determine if ClassA
defines (responds to) methodA
.
ClassA可以定义methodA,也可以不定义methodA。如果我使用ClassA的实例和实例方法,我可以使用respondsToSelector:测试实例。然而,在这种情况下,我无法想出任何干净的方法来确定ClassA是否定义(响应)methodA。
EDIT: I was silly and did not make my example specific enough, which meant the answer to the question was not exactly the solution to my problem -- so I am including a bit more code and the warning I am getting:
编辑:我太愚蠢了,而且我的例子不够具体,这意味着问题的答案并不完全是我问题的解决方案——所以我要增加一些代码,并得到警告:
Class <ProtocolA> classRef = [ClassA class];
if([classRef respondsToSelector:@selector(methodA)]) {}
The above code throws the following warning: " Instance method 'respondsToSelector:
' found instead of class method 'respondsToSelector:
'"
上面的代码抛出以下警告:“实例方法'respondsToSelector:' find而不是类方法'respondsToSelector:'”
I only just now noticed that if I explicitly cast classRef
to (Class)
then the warning goes away. I still find that odd.
我刚刚注意到,如果显式地将classRef转换为(Class),那么警告就会消失。我还是觉得这很奇怪。
1 个解决方案
#1
7
[[instance class] respondsToSelector:@selector(methodA)]
[[实例类]respondstoselectorismemberofclass:@ selector methodA()
Every instance of a class has a pointer to it's class object which can be retrieved by calling class
. This object (classes are objects in Objective C) can be probed with respondsToSelector:
just like any other object.
类的每个实例都有一个指向类对象的指针,可以通过调用类来检索类。这个对象(类是Objective C中的对象)可以使用respondsToSelector:就像任何其他对象一样。
#1
7
[[instance class] respondsToSelector:@selector(methodA)]
[[实例类]respondstoselectorismemberofclass:@ selector methodA()
Every instance of a class has a pointer to it's class object which can be retrieved by calling class
. This object (classes are objects in Objective C) can be probed with respondsToSelector:
just like any other object.
类的每个实例都有一个指向类对象的指针,可以通过调用类来检索类。这个对象(类是Objective C中的对象)可以使用respondsToSelector:就像任何其他对象一样。