C's callback function:
CallBack.h
1), declare a dosomethingcount function, the parameter is a (no return value, 1 int parameter) function.
void Dstcount (void (*callback) (int data_i32));
Callback.c
1), in the Dosomethingcount function, increment the number of runs, and call the parameter--function.
void Dstcount (void (*callback) (int data_i32)) { static int numb = 0; numb++; (*callback) (numb);}
Main.c
1), define a customdosomethingcount function, print the data.
void Customdstcount (int data_i32) { printf ("%d\n", DATA_I32);}
2), main function, run CallBack.h's Dstcount function, the parameter is the Customdstcount function in main.
while (1) { dstcount (customdstcount);}
Block of OC:
MyButton.h (inherited from UIButton):
1), define a block of the number of parameters, type.
typedef void (^buttonblock) (int data_i32);
2), declare a dosomethingcount function with the block parameter. (Note that there is no need to add *, class with the habit, parameters readily add a *)
-(void) Dstcount: (Buttonblock) mybuttonblockptr;
MYBUTTON.M (inherited from UIButton):
1), in the Dosomethingcount function, increment the number of runs, and call the block parameter.
-(void) Dstcount: (buttonblock) mybuttonblockptr{ static int numb = 0; numb++; Mybuttonblockptr (numb);}
ROOTVIEWCONTROL.M (Self.window.rootViewController):
1), Viewdidload function, define a (100,100,100,100), red button instance, button to add the event, the button is added to the Self.view.
MyButton *tempbutton = [[MyButton alloc]initwithframe:cgrectmake (+, +, +)]; Tempbutton.backgroundcolor = [Uicolor redcolor]; [Tempbutton addtarget:self Action: @selector (Mybuttonclick:) forcontrolevents:uicontroleventtouchupinside]; [Self.view Addsubview:tempbutton];
2), button click Call, Call MyButton in the Dstcount function, block parameters directly input.
-(void) Mybuttonclick: (mybutton*) button{ [button dstcount:^ (int data_i32) { printf ("%d\n", data_i32); }];}
Photo Supplement:
C callback function:
1), CALLBACK.C
2), CallBack.h
3), MAIN.C
Block of OC
1), MyButton.h
2), MYBUTTON.M
3), ROOTVIEWCONTROL.M
4), run
Embedded &ios: callback function (C) vs. block (OC) parameter/function comparison