Using Block in iOS to implement function callback

Source: Internet
Author: User

Using Block in iOS to implement function callback

In fact, the Block in iOS is the function pointer in C ++, And the implementation methods are the same. Below is a simple practice.

First, create a callback class.

BlockStudy. h

//// BlockStudy. h // BlockStudy /// Created by du jia on 11/11/14. // Copyright (c) 2014 du jia. all rights reserved. // # import
 
  
@ Interface BlockStudy: NSObjecttypedef void (^ TestBlock) (); @ property (nonatomic, strong) TestBlock testBlock;-(void) StartBlock; @ end
 
BlockStudy. m

//// BlockStudy. m // BlockStudy /// Created by du jia on 11/11/14. // Copyright (c) 2014 du jia. all rights reserved. // # import "BlockStudy. h "@ implementation BlockStudy-(void) test {if (_ testBlock) {_ testBlock () ;}}-(void) StartBlock {[self defined mselector: @ selector (test) withObject: nil afterDelay: 2.0];} @ end


Call class ViewController. m

//// ViewController. m // BlockStudy /// Created by du jia on 11/11/14. // Copyright (c) 2014 du jia. all rights reserved. // # import "ViewController. h "# import" BlockStudy. h "@ interface ViewController () @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. blockStudy * block = [[BlockStudy alloc] init]; block. testBlock = ^ () {UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @ "Block learning" message: @ "test successful" delegate: self cancelButtonTitle: @ "cancel" otherButtonTitles: @ "OK", nil]; [alert show] ;}; [block StartBlock] ;}- (void) didReceiveMemoryWarning {[super didreceivemorywarning]; // Dispose of any resources that can be recreated .} @ end






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.