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

后端 未结 3 791
轻奢々
轻奢々 2020-12-30 04:42

The only difference I observed on my own is that respondsToSelector\'s receiver can either be a class or an instance, while instancesRespondToSelector

相关标签:
3条回答
  • 2020-12-30 05:16

    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.

    0 讨论(0)
  • 2020-12-30 05:27

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

    0 讨论(0)
  • 2020-12-30 05:33

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

    0 讨论(0)
提交回复
热议问题