[英]Cast an instance of a class to a @protocol in Objective-C
我有一个 object(一个 UIViewController),它可能符合也可能不符合我定义的协议。
我知道我可以确定 object 是否符合协议,然后安全地调用方法:
if([self.myViewController conformsToProtocol:@protocol(MyProtocol)]) {
[self.myViewController protocolMethod]; // <-- warning here
}
但是,XCode 显示警告:
warning 'UIViewController' may not respond to '-protocolMethod'
防止此警告的正确方法是什么? 我似乎无法将self.myViewController
为MyProtocol
class。
这样做的正确方法是:
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".
这样,编译器将为您提供正确的vc
类型检查 - 如果调用了未在UIViewController
或<MyProtocol>
上声明的任何方法,编译器只会向您发出警告。 id
仅应在您不知道正在转换的 object 的类/类型的情况下使用。
你可以像这样投射它:
if([self.myViewController conformsToProtocol:@protocol(MyProtocol)])
{
id<MyProtocol> p = (id<MyProtocol>)self.myViewController;
[p protocolMethod];
}
这也让我有点失望。 在 Objective-C 中,协议本身不是类型,因此您需要指定id
(或其他类型,例如NSObject
)以及所需的协议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.