Embedded & iOS: Comparison of callback function (C) and block (OC) parameters/functions, embedded training
C 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, increase the number of running times 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 to print data.
void customDSTCount(int data_i32){ printf("%d\n",data_i32);}
2) in the main function, run the DSTCount function of callBack. h. The parameter is the customDSTCount function in main.
while (1){ DSTCount(customDSTCount);}
OC Block:
MyButton. h (inherited from UIButton ):
1) define the number and type of parameters of a Block.
typedef void(^ButtonBlock)(int data_i32);
2) declare a doSomeThingCount function with Block parameters. (Note: you do not need to add * here. The class is used to adding a parameter * at will *)
-(void)DSTCount:(ButtonBlock)myButtonBlockPTR;
MyButton. m (inherited from UIButton ):
1) In the doSomeThingCount function, increase the number of running times and call the Block parameter.
-(void)DSTCount:(ButtonBlock)myButtonBlockPTR{ static int numb = 0; numb++; myButtonBlockPTR(numb);}
RootViewControl. m (self. window. rootViewController ):
1) The viewDidLoad function defines a (100,100,100,100), red button instance, button to add events, and button to self. view.
MyButton *tempButton = [[MyButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)]; tempButton.backgroundColor = [UIColor redColor]; [tempButton addTarget:self action:@selector(mybuttonClick:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:tempButton];
2) click the button to call the DSTCount function in MyButton. The Block parameter is directly input.
-(void)mybuttonClick:(MyButton*)button{ [button DSTCount:^(int data_i32) { printf("%d\n",data_i32); }];}
Image supplement:
C callback function:
1) CallBack. C
2) CallBack. h
3). main. c
OC Block
1) MyButton. h
2) MyButton. m
3) RootViewControl. m
4) Run