在自定义的delegate实现中注意 判断delegate有没有实现响应的@protocol方法
我们在自定义的delegate实现中,会判断delegate是否为空,然后如果不是为空,就调用相应的delegate的函数:
例如:
if(delegate_ != nil)
{
[delegate_ View:self touchesBegan:touches withEvent:event];
}
{
[delegate_ View:self touchesBegan:touches withEvent:event];
}
上面的实现,直接就是判断delegate是否为空,如果不为空,调用protocol的 View:touchesBegan:withEvent:方法。
但是当有一个类,实现了 protocol,也设置了delegate_为这个类的对象,但是这个类没有实现 View:touchesBegan:withEvent:方法(这个方法被protocol设置为option)的时候,这个地方会crash.
我以为设置了protocol的option参数就没有问题,其实要判断这个delegate是否实现了这个协议方法:
正确的代码如下:
if(delegate_ != nil)
{
if([(NSObject *)delegate_ respondsToSelector:@selector(foolTapView:touchesBegan:withEvent: )] == YES )
{
[delegate_ View:self touchesBegan:touches withEvent:event];
}
}
{
if([(NSObject *)delegate_ respondsToSelector:@selector(foolTapView:touchesBegan:withEvent: )] == YES )
{
[delegate_ View:self touchesBegan:touches withEvent:event];
}
}
respondsToSelector是一个NSObject方法,所以delegate要强制转换为NSObject * .