The only difference I observed on my own is that respondsToSelector
's receiver can either be a class or an instance, while instancesRespondToSelector
can only have a class receiver. What else makes them different, though? Are there any performance issues with one or the other?
Under the hood, -[NSObject respondsToSelector:]
is implemented like this:
- (BOOL)respondsToSelector:(SEL)aSelector {
return class_respondsToSelector([self class], aSelector);
}
and +[Class instancesRespondToSelector:]
is implemented like this:
+ (BOOL)instancesRespondToSelector:(SEL)aSelector {
return class_respondsToSelector(self, aSelector);
}
(I used Hopper on CoreFoundation to figure this out.)
So, there's basically no difference. However, you can override respondsToSelector:
in your own class to return YES or NO on a per-instance basis (NSProxy
does this). You can't do that with instancesRespondToSelector:
.
One difference is respondsToSelector
can't tell you if an instance inherits a method from its superclass, so if you want to do something like [super respondsToSelector:_cmd];
it wont work, you need to to [[self superclass] instancesRespondToSelector:_cmd];
respondsToSelector:
is an instance method and determines whether an object, which could be an instance of a class or a class object, responds to a selector. When you pass a instance you are testing for an instance method, when you pass a class object you are testing for a class method.
instancesRespondToSelector:
is a class method and determines if instances of a class respond to a selector. It allows testing for an instance method given a class and without having an instance of that class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With