在自定义的delegate实现中注意 判断delegate有没有实现响应的@protocol方法

                     在自定义的delegate实现中注意 判断delegate有没有实现响应的@protocol方法

       我们在自定义的delegate实现中,会判断delegate是否为空,然后如果不是为空,就调用相应的delegate的函数:

    例如:
     if(delegate_ != nil)
    {
       [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];
    }
}

respondsToSelector是一个NSObject方法,所以delegate要强制转换为NSObject * .
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值