[Comparison of IOS block and delegate]

Source: Internet
Author: User

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]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.