Technical Exchange new QQ Group: 414971585
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
- @protocol updatealertdelegate
- -(void) Updatealert: (NSString *tltle);
- @end
- @interface Timercontrol:nsobject
- Delegate variable definition
- @property (nonatomic, weak) ID delegate;
- Block
- typedef void (^updatealertblock) (NSString *tltle);
- @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:@ "This is title"];//Delegate Update UI
- Block instead of delegate
- if (Self.updatealertblock)
- {
- Self.updatealertblock (@ "This is title");
- }
- }
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 block
- Timer.updatealertblock = ^ (NSString *title)
- {
- Uialertview *alert=[[uialertview alloc] Initwithtitle:title message:@ "Time to" Delegate:self Cancelbuttontitle:nil otherbuttontitles:@ "OK", nil];
- Alert.alertviewstyle=uialertviewstyledefault;
- [Alert show];
- };
- [Timer startthetimer];//start timer, timer 5 trigger
- }
The delegate object implements the method of the Protocol declaration, which is called by the delegate object
-(void) Updatealert: (NSString *title)
{
Uialertview *alert=[[uialertview alloc] Initwithtitle:title message:@ "Time to" delegate:self Cancelbuttontitle: nilotherbuttontitles:@ "OK", nil];
Alert.alertviewstyle=uialertviewstyledefault;
[Alert show];
}
IOS value Delegate (delegate) vs. block comparison