• iOS 传值 委托(delegate)和block 对比


     

     技术交流QQ群:414971585

     

    这篇文章建议和前一篇一起看, 另外先弄清楚IOS的block是神马东东。

    委托和block是IOS上实现回调的两种机制。Block基本可以代替委托的功能,而且实现起来比较简洁,比较推荐能用block的地方不要用委托。

    本篇的demo和前一篇是同一个,可以到github上下载不同的版本, 源码下载地址:

    https://github.com/pony-maggie/DelegateDemo

    A类(timeControl类)的头文件先要定义block,代码如下:

     
    1. //委托的协议定义  
    2. @protocol UpdateAlertDelegate   
    3. - (void)updateAlert:(NSString *tltle);  
    4. @end  
    5.   
    6.   
    7.   
    8. @interface TimerControl : NSObject  
    9. //委托变量定义  
    10. @property (nonatomic, weak) id delegate;  
    11.   
    12.   
    13. //block  
    14. typedef void (^UpdateAlertBlock)(NSString *tltle);  
    15. @property (nonatomic, copy) UpdateAlertBlock updateAlertBlock;  
    16.   
    17. - (void) startTheTimer;  
    18.      
    19. @end  


    A类的实现文件,原来用委托的地方改成调用block:

     
    1. - (void) timerProc  
    2. {  
    3.     //[self.delegate updateAlert:@"this is title"];//委托更新UI  
    4.     //block代替委托  
    5.     if (self.updateAlertBlock)  
    6.     {  
    7.         self.updateAlertBlock(@"this is title");  
    8.     }  
    9. }  


    再来看看视图类,实现block即可:

     
    1. - (void)viewDidLoad  
    2. {  
    3.     [super viewDidLoad];  
    4.     // Do any additional setup after loading the view, typically from a nib.  
    5.     TimerControl *timer = [[TimerControl alloc] init];  
    6.     timer.delegate = self; //设置委托实例  
    7.       
    8.     //实现block  
    9.     timer.updateAlertBlock = ^(NSString *title)  
    10.     {  
    11.         UIAlertView *alert=[[UIAlertView alloc] initWithTitle:title message:@"时间到" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];  
    12.           
    13.         alert.alertViewStyle=UIAlertViewStyleDefault;  
    14.         [alert show];  
    15.     };  
    16.       
    17.       
    18.       
    19.     [timer startTheTimer];//启动定时器,定时5触发  
    20. }  

      //"被委托对象"实现协议声明的方法,由"委托对象"调用

      - (void)updateAlert:(NSString *title)

      {

          UIAlertView *alert=[[UIAlertView alloc] initWithTitle:title message:@"时间到" delegate:self cancelButtonTitle:nilotherButtonTitles:@"确定",nil];

          

          alert.alertViewStyle=UIAlertViewStyleDefault;

          [alert show];

      }

  • 相关阅读:
    SpringJMS解析2-JmsTemplate
    SpringJMS解析1-使用示例
    SpringHttpInvoker解析3-客户端实现
    算法笔记_084:蓝桥杯练习 11-1实现strcmp函数(Java)
    算法笔记_083:蓝桥杯练习 合并石子(Java)
    算法笔记_082:蓝桥杯练习 12-1三角形(Java)
    算法笔记_081:蓝桥杯练习 算法提高 矩阵乘法(Java)
    算法笔记_080:蓝桥杯练习 队列操作(Java)
    算法笔记_079:蓝桥杯练习 区间k大数查询(Java)
    算法笔记_078:蓝桥杯练习 最大最小公倍数(Java)
  • 原文地址:https://www.cnblogs.com/heheda/p/4285424.html
Copyright © 2020-2023  润新知