Original: http://blog.sina.com.cn/s/blog_9e8867eb0102uykn.html
This article is suggested to look together with the previous article, the other first to understand the iOS block is God horse East.
Delegates and blocks are two mechanisms of implementing callbacks on iOS. Block can basically replace the function of the delegate, and the implementation is relatively concise, it is recommended to use the block of the place do not use the delegation.
This demo and the previous one is the same, you can download different versions of GitHub, source code:
Https://github.com/pony-maggie/DelegateDemo
The header file of Class A (TimeControl Class) first defines block, the code is as follows:
//protocol definitions for delegates@protocolUpdatealertdelegate <nsobject>-(void) Updatealert;@end@interfaceTimercontrol:nsobject//delegate Variable definition@property (nonatomic, weak)ID<UpdateAlertDelegate>Delegate;//Blocktypedefvoid(^Updatealertblock) (); @property (nonatomic, copy) Updatealertblock Updatealertblock;- (void) Startthetimer; @end
The implementation file of Class A, where the original delegate is changed to call Block:
-(void) timerproc{ //[self.delegate Updatealert]; // delegate Update UI // block instead of delegate if (Self.updatealertblock) { self.updatealertblock (); }}
Take a look at the view class and implement block:
- (void) viewdidload{[Super Viewdidload]; //additional setup after loading the view, typically from a nib.Timercontrol *timer =[[Timercontrol alloc] init]; Timer.Delegate= self;//set up a delegate instance//Implement blockTimer.updatealertblock = ^() {Uialertview*alert=[[uialertview Alloc] Initwithtitle:@"Tips"Message@"Time to" Delegate: Self Cancelbuttontitle:nil otherbuttontitles:@"Determine", nil]; Alert.alertviewstyle=Uialertviewstyledefault; [Alert show]; }; [Timer Startthetimer];//Start Timer, timer 5 trigger}
[Comparison of IOS block and delegate]