在Objective-C中将类的实例强制转换为@protocol [英] Cast an instance of a class to a @protocol in Objective-C

查看:79
本文介绍了在Objective-C中将类的实例强制转换为@protocol的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象(UIViewController),该对象可能符合也可能不符合我定义的协议.

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
}

但是,XCode显示警告:

However, XCode shows a warning:

warning 'UIViewController' may not respond to '-protocolMethod'

预防此警告的正确方法是什么?我似乎无法将self.myViewController转换为MyProtocol类.

What's the right way to prevent this warning? I can't seem to cast self.myViewController as a MyProtocol 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];
}

UIViewController <MyProtocol> *类型转换转换为"vc是符合MyProtocol的UIViewController对象",而使用id <MyProtocol>转换为"vc是符合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".

通过这种方式,编译器将为您提供对vc的正确类型检查-仅当调用未在UIViewController<MyProtocol>上声明的任何方法时,编译器才会向您发出警告. id仅在您不知道要强制转换的对象的类/类型的情况下使用.

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.

这篇关于在Objective-C中将类的实例强制转换为@protocol的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆