何时在objective-c中使用respondsToSelector [英] when to use respondsToSelector in objective-c

查看:120
本文介绍了何时在objective-c中使用respondsToSelector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

- (void)someMethod
{
    if ( [delegate respondsToSelector:@selector(operationShouldProceed)] )
    {
        if ( [delegate operationShouldProceed] )
        {
            // do something appropriate
        }
    }
}

文档说:


预防措施是必要的仅适用于正式协议中的可选方法或非正式协议的方法

The precaution is necessary only for optional methods in a formal protocol or methods of an informal protocol

这是什么意思?如果我使用正式协议,我可以使用 [委托myMethod]

What does it mean? If I use a formal protocol I can just use [delegate myMethod]?

推荐答案

您只需在以下情况下使用它:检查对象是否实现了您要调用的方法。 通常这是在您有可选方法或非正式协议时完成的。

You use it pretty much just when you think you need to: to check to see if an object implements the method you are about to call. Usually this is done when you have an optional methods or an informal protocol.

当我编写必须与委托对象通信的代码时,我只使用过 respondsToSelector

I've only ever used respondsToSelector when I'm writing code that must communicate with a delegate object.

if ([self.delegate respondsToSelector:@selector(engineDidStartRunning:)]) {
        [self.delegate engineDidStartRunning:self];
    }

您有时会想要使用 respondsToSelector 对任何返回的方法和 id 或泛型 NSObject 你不知道什么类的返回的对象是。

You sometimes would want to use respondsToSelector on any method that returns and id or generic NSObject where you aren't sure what the class of the returned object is.

这篇关于何时在objective-c中使用respondsToSelector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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