MLQ
MLQ

Reputation: 13511

What is the difference between instancesRespondToSelector and respondsToSelector in 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?

Upvotes: 16

Views: 6272

Answers (3)

rob mayoff
rob mayoff

Reputation: 385580

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

Upvotes: 26

CRD
CRD

Reputation: 53000

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.

Upvotes: 4

wattson12
wattson12

Reputation: 11174

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

Upvotes: 9

Related Questions