gpt4 book ai didi

objective-c - 何时在 Objective-C 中使用 respondsToSelector

转载 作者:IT老高 更新时间:2023-10-28 11:27:46 24 4
gpt4 key购买 nike

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

documentation说:

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

这是什么意思?如果我使用正式协议(protocol),我可以只使用 [delegate myMethod]?

最佳答案

您几乎只在您认为需要时使用它:检查对象是否实现了您将要调用的方法。 通常当您有可选方法或非正式协议(protocol)时会这样做。

我只在编写必须与委托(delegate)对象通信的代码时使用过 respondsToSelector

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

您有时会希望在任何返回的方法上使用 respondsToSelector 以及您不确定类是什么的 id 或通用 NSObject返回的对象是。

关于objective-c - 何时在 Objective-C 中使用 respondsToSelector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3697058/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com