As kubi respondsToSelector is mentioned, it is usually used when you have an instance of a method that conforms to the protocol.
// Extend from the NSObject protocol so it is safe to call `respondsToSelector` @protocol MyProtocol <NSObject> // @required by default - (void) requiredMethod; @optional - (void)optionalMethod; @end
Given an instance of this protocol, we can safely call any required method.
id <MyProtocol> myObject = ... [myObject requiredMethod];
However, optional methods may or may not be implemented, so you need to check them at runtime.
if ([myObject respondsToSelector:@selector(optionalMethod)]) { [myObject optionalMethod]; }
Doing this will prevent a failure with an unrecognized selector.
In addition, you must declare the protocols as an extension of NSObjects, i.e.
@protocol MyProtocol <NSObject>
This is because the NSObject protocol declares the respondsToSelector: selector. Otherwise, Xcode will consider it unsafe.
Robert 03 Feb '14 at 9:12 2014-02-03 09:12
source share