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