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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/617616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:13:14  来源:igfitidea点击:

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

objective-cprotocols

提问by Ford

I have an object (a UIViewController) which may or may not conform to a protocol I've defined.

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

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:

但是,XCode 显示警告:

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

What's the right way to prevent this warning? I can't seem to cast self.myViewControlleras a MyProtocolclass.

防止此警告的正确方法是什么?我似乎无法self.myViewController作为一个MyProtocol班级演员。

回答by Nick Forge

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".

UIViewController <MyProtocol> *型铸造转换为“VC是一个UIViewController对象符合MyProtocol”,而使用id <MyProtocol>转换为“VC是一个未知类符合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 UIViewControlleror <MyProtocol>is called. idshould only be used in the situation if you don't know the class/type of the object being cast.

这样,编译器将为您提供正确的类型检查vc- 编译器只会在任何未声明UIViewController或未<MyProtocol>调用的方法时向您发出警告。id如果您不知道正在转换的对象的类/类型,则应仅在这种情况下使用。

回答by Andy

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)以及您想要的协议。