In fact, the block in iOS is a function pointer in C + +, the implementation is the same way, a simple practice is posted below.
First, create a callback class
BlockStudy.h
blockstudy.h// blockstudy//// Created by du Jia Li on 11/11/14.// Copyright (c) 2014 DuPont. All rights reserved.//#import <Foundation/Foundation.h> @interface blockstudy:nsobjecttypedef Void (^testblock) (); @property (nonatomic, Strong) Testblock testblock;-(void) startblock; @end
Blockstudy.m
blockstudy.m// blockstudy//// Created by du Jia Li on 11/11/14.// Copyright (c) 2014 DuPont. All rights reserved.//#import "BlockStudy.h" @implementation blockstudy-(void) test{ if (_testblock) { _ Testblock (); }} -(void) startblock{ [self performselector: @selector (Test) Withobject:nil afterdelay:2.0];} @end
Call Class VIEWCONTROLLER.M
viewcontroller.m// blockstudy//// Created by du Jia Li on 11/11/14.// Copyright (c) 2014 DuPont. All rights reserved.//#import "ViewController.h" #import "BlockStudy.h" @interface Viewcontroller () @ End@implementation viewcontroller-(void) viewdidload { [super viewdidload]; 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 succeeded" Delegate:self cancelbuttontitle:@ "Cancel" otherbuttontitles:@ "OK", nil]; [Alert show]; }; [Block Startblock];} -(void) didreceivememorywarning { [super didreceivememorywarning]; Dispose of any resources the can be recreated.} @end
IOS uses block to implement function callbacks