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

后端 未结 2 1211
半阙折子戏
半阙折子戏 2020-12-12 12:07

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 s

相关标签:
2条回答
  • 2020-12-12 12:55

    The correct way to do this is to do:

    if ([self.myViewController conformsToProtocol:@protocol(MyProtocol)])
    {
            UIViewController <MyProtocol> *vc = (UIViewController <MyProtocol> *) self.myViewController;
            [vc protocolMethod];
    }
    

    The UIViewController <MyProtocol> * type-cast translates to "vc is a UIViewController object that conforms to MyProtocol", whereas using id <MyProtocol> translates to "vc is an object of an unknown class that conforms to MyProtocol".

    This way the compiler will give you proper type checking on vc - the compiler will only give you a warning if any method that's not declared on either UIViewController or <MyProtocol> is called. id should only be used in the situation if you don't know the class/type of the object being cast.

    0 讨论(0)
  • 2020-12-12 13:12

    You can cast it like this:

    if([self.myViewController conformsToProtocol:@protocol(MyProtocol)])
    {
        id<MyProtocol> p = (id<MyProtocol>)self.myViewController;
        [p protocolMethod];
    }
    

    This threw me for a bit, too. In Objective-C, the protocol isn't the type itself, so you need to specify id (or some other type, such as NSObject) along with the protocol that you want.

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