Cast an instance of a class to a @protocol in Objective-C

Posted by Ford on Stack Overflow See other posts from Stack Overflow or by Ford
Published on 2009-03-06T03:32:24Z Indexed on 2010/04/15 11:13 UTC
Read the original article Hit count: 292

Filed under:
|

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

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about protocol