iphone - 如何检查是否设置了自定义委托(delegate)?

标签 iphone ios cocoa-touch delegates

我在 RandomClass.mRandomClass.h 中实现了自定义委托(delegate) RandomClassDelegate。现在我需要实现委托(delegate)变量,并让它调用协议(protocol)中的方法,如下所示:

[self.delegate randomClassDelegateMethod];

显然,如果从未设置delegate,这将导致程序崩溃并导致运行时错误。显而易见的解决方案是:

if (delegate)
{
[self.delegate randomClassDelegateMethod];
}

但我想知道这是否是正确的模式,或者是否有更好的方法来做到这一点,可能在协议(protocol)中或其他地方?

最佳答案

您应该使用 -respondsToSelector: 来检查委托(delegate)是否有效:

if ([delegate respondsToSelector:@selector(myDelegateMethod)])
     [delegate myDelegateMethod];

不要担心检查 nil,因为您可以向 nil 对象发送消息,它什么也不做。

关于iphone - 如何检查是否设置了自定义委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10923404/

相关文章:

ios - 无法找到对象在数组中的位置?

ios - 在 Objective C 中调用父类(super class)方法的时机是否重要?

iphone - 关于 UITableView

ios - 将所有屏幕方向锁定为纵向,除了 1

iPhone 用户界面自动化 : Dynamically Added UI Elements Not Displayed When Executing logElementTree()

iphone - 应用程序在屏幕关闭时不播放声音,但仍按应有的方式执行其他操作?

iphone - 如何测试我正在创建的iOS应用程序并模拟中国用户?

iphone - 无法在 View 之间读取 NSUserDefaults 数据

ios - 为数字添加逗号分隔符,键入时每隔三个数字

ios - 将 View 作为参数添加到自定义 ViewModifier