简体   繁体   English

将 class 的实例转换为 Objective-C 中的 @protocol

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

I have an object (a UIViewController) which may or may not conform to a protocol I've defined.我有一个 object(一个 UIViewController),它可能符合也可能不符合我定义的协议。

I know I can determine if the object conforms to the protocol, then safely call the method:我知道我可以确定 object 是否符合协议,然后安全地调用方法:

if([self.myViewController conformsToProtocol:@protocol(MyProtocol)]) {
    [self.myViewController protocolMethod]; // <-- warning here
}

However, XCode shows a warning:但是,XCode 显示警告:

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.我似乎无法将self.myViewControllerMyProtocol class。

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". 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.这样,编译器将为您提供正确的vc类型检查 - 如果调用了未在UIViewController<MyProtocol>上声明的任何方法,编译器只会向您发出警告。 id should only be used in the situation if you don't know the class/type of the object being cast. id仅应在您不知道正在转换的 object 的类/类型的情况下使用。

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.在 Objective-C 中,协议本身不是类型,因此您需要指定id (或其他类型,例如NSObject )以及所需的协议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM