iOS 傳值 委託(delegate)和block 對比

 

 技術交流QQ羣:414971585git

 

這篇文章建議和前一篇一塊兒看, 另外先弄清楚IOS的block是神馬東東。github

 

委託和block是IOS上實現回調的兩種機制。Block基本能夠代替委託的功能,並且實現起來比較簡潔,比較推薦能用block的地方不要用委託。this

 

本篇的demo和前一篇是同一個,能夠到github上下載不一樣的版本, 源碼下載地址:atom

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

 

 

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:get

 

 
  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. }  

    //"被委託對象"實現協議聲明的方法,由"委託對象"調用it

    - (void)updateAlert:(NSString *title)io

    {

        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:title message:@"時間到" delegate:self cancelButtonTitle:nilotherButtonTitles:@"肯定",nil];

        

        alert.alertViewStyle=UIAlertViewStyleDefault;

        [alert show];

    }

相關文章
相關標籤/搜索