這篇文章建議和前一篇一塊兒看, 另外先弄清楚IOS的block是神馬東東。github
委託和block是IOS上實現回調的兩種機制。Block基本能夠代替委託的功能,並且實現起來比較簡潔,比較推薦能用block的地方不要用委託。this
本篇的demo和前一篇是同一個,能夠到github上下載不一樣的版本, 源碼下載地址:atom
https://github.com/pony-maggie/DelegateDemospa
A類(timeControl類)的頭文件先要定義block,代碼以下:對象
- //委託的協議定義
- @protocol UpdateAlertDelegate
- - (void)updateAlert:(NSString *tltle);
- @end
-
-
-
- @interface TimerControl : NSObject
- //委託變量定義
- @property (nonatomic, weak) id delegate;
-
-
- //block
- typedef void (^UpdateAlertBlock)(NSString *tltle);
- @property (nonatomic, copy) UpdateAlertBlock updateAlertBlock;
-
- - (void) startTheTimer;
-
- @end
A類的實現文件,原來用委託的地方改爲調用block:get
- - (void) timerProc
- {
- //[self.delegate updateAlert:@"this is title"];//委託更新UI
- //block代替委託
- if (self.updateAlertBlock)
- {
- self.updateAlertBlock(@"this is title");
- }
- }
再來看看視圖類,實現block便可:源碼
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- // Do any additional setup after loading the view, typically from a nib.
- TimerControl *timer = [[TimerControl alloc] init];
- timer.delegate = self; //設置委託實例
-
- //實現block
- timer.updateAlertBlock = ^(NSString *title)
- {
- UIAlertView *alert=[[UIAlertView alloc] initWithTitle:title message:@"時間到" delegate:self cancelButtonTitle:nil otherButtonTitles:@"肯定",nil];
-
- alert.alertViewStyle=UIAlertViewStyleDefault;
- [alert show];
- };
-
-
-
- [timer startTheTimer];//啓動定時器,定時5觸發
- }
//"被委託對象"實現協議聲明的方法,由"委託對象"調用it
- (void)updateAlert:(NSString *title)io
{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:title message:@"時間到" delegate:self cancelButtonTitle:nilotherButtonTitles:@"肯定",nil];
alert.alertViewStyle=UIAlertViewStyleDefault;
[alert show];
}