Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

objective-c

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.

like image 998
Mathew Avatar asked Nov 22 '25 11:11

Mathew


1 Answers

[[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.

like image 83
Lance Avatar answered Nov 25 '25 10:11

Lance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!