Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do class_respondsToSelector and respondsToSelector behave different when sent to Class?

I have spent quite some time trying to figure out how class_respondsToSelector and respondsToSelector can give different results. Consider the following class:

@interface Dummy : NSObject
- (void)test;
@end

@implementation Dummy
- (void)test {}
@end

My scenario is that I try to determine if a class responds to a certain class method. This piece reproduces the problem:

Class class = [Dummy class];
if (class_respondsToSelector(class, @selector(test)))
    NSLog(@"class_respondsToSelector: YES");
else
    NSLog(@"class_respondsToSelector: NO");
if ([class respondsToSelector:@selector(test)])
    NSLog(@"respondsToSelector: YES");
else
    NSLog(@"respondsToSelector: NO");

If I remove the declaration and implementation of -test, the output of the above is NO and NO as expected. However, running it as it reads above (including -test), the output produced is the following:

class_respondsToSelector: YES

respondsToSelector: NO

The documentation says nothing about whether respondsToSelector works for instances only, just that it indicates whether the receiver implements..., hence I am unable to determine whether this is correct behavior or not. Am I missing something?

Update

Graham Lee provided this link to a great discussion on the problem.

like image 831
Kasper Munck Avatar asked Feb 16 '23 11:02

Kasper Munck


1 Answers

The question asked by class_respondsToSelector() is "Do instances of this class respond to this selector?"

The question asked by -[NSObject respondsToSelector:] is "Does this particular instance (which is the "reciever") respond to this selector?"

You're sending respondsToSelector: to a class object, which is itself an instance of its metaclass, and asking about that particular object.

To see the same results as class_respondsToSelector(), either use +[NSObject instancesRespondToSelector:] or get an instance of the class.

like image 87
jscs Avatar answered Apr 28 '23 00:04

jscs