Mathew
Mathew

Reputation: 1798

How can an Objective-C Class be tested to determine if it responds to a static selector (a class method)?

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.

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:'"

I only just now noticed that if I explicitly cast classRef to (Class) then the warning goes away. I still find that odd.

Upvotes: 3

Views: 526

Answers (1)

Lance
Lance

Reputation: 9012

[[instance class] respondsToSelector:@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.

Upvotes: 7

Related Questions