我在 RandomClass.m
和 RandomClass.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/