Cast an instance of a class to a @protocol in Objective-C
- by Ford
I have an object (a UIViewController) which may or may not conform to a protocol I've defined.
I know I can determine if the object conforms to the protocol, then safely call the method:
if([self.myViewController conformsToProtocol:@protocol(MyProtocol)]) {
[self.myViewController protocolMethod]; // <-- warning here
}
However, XCode shows a warning:
warning 'UIViewController' may not respond to '-protocolMethod'
What's the right way to prevent this warning? I can't seem to cast self.myViewController as a MyProtocol class.
Update
Andy's answer below is close, but includes an unneccesary '*'. The following works:
[(id<MyProtocol>)self.myViewController protocolMethod];