Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between instancesRespondToSelector and respondsToSelector in Objective-C?

Tags:

objective-c

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?

like image 698
MLQ Avatar asked Jul 20 '12 07:07

MLQ


3 Answers

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

like image 95
rob mayoff Avatar answered Oct 22 '22 04:10

rob mayoff


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];

like image 9
wattson12 Avatar answered Oct 22 '22 06:10

wattson12


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.

like image 4
CRD Avatar answered Oct 22 '22 04:10

CRD