zoukankan      html  css  js  c++  java
  • 嵌入式&iOS:回调函数(C)与block(OC)传 参/函数 对比

    嵌入式&iOS:回调函数(C)与block(OC)传 参/函数 对比

    C的回调函数:

    callBack.h

    1)、声明一个doSomeThingCount函数,参数为一个(无返回值,1个int参数的)函数。

    1
    void DSTCount(void(*CallBack)(int data_i32));

    callBack.c

    1)、在doSomeThingCount函数,对运行次数自增,并调用参数--函数。

    1
    2
    3
    4
    5
    6
    void DSTCount(void(*CallBack)(int data_i32))
    {
        static int numb = 0;
        numb++;
        (*CallBack)(numb);
    }

     

    main.c

    1)、定义一个customdoSomeThingCount函数,打印数据。

    1
    2
    3
    4
    void customDSTCount(int data_i32)
    {
        printf("%d ",data_i32);
    }

    2)、main函数里,运行 callBack.h 的 DSTCount 函数,参数为main里的customDSTCount函数。

    1
    2
    3
    4
    while (1)
    {
        DSTCount(customDSTCount);
    }

    OC的Block:

    MyButton.h(继承于UIButton):

    1)、定义一个Block的参数数量、类型。

    1
    typedef void(^ButtonBlock)(int data_i32);

    2)、声明一个doSomeThingCount函数,带Block参数。(注意,这里不需要加*,类用习惯了,参数随手就加个*)

    1
    -(void)DSTCount:(ButtonBlock)myButtonBlockPTR;

    MyButton.m(继承于UIButton):

    1)、在doSomeThingCount函数,对运行次数自增,并调用Block参数。

    1
    2
    3
    4
    5
    6
    -(void)DSTCount:(ButtonBlock)myButtonBlockPTR
    {
        static int numb = 0;
        numb++;
        myButtonBlockPTR(numb);
    }

     

    RootViewControl.m(self.window.rootViewController):

    1)、viewDidLoad函数,定义一个(100,100,100,100)、红色的按钮实例,按钮添加事件,把按钮加到self.view上。

    1
    2
    3
    4
    5
    6
    7
    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)、按钮点击调用,调用MyButton里的DSTCount函数,Block参数直接输入。

    1
    2
    3
    4
    5
    6
    -(void)mybuttonClick:(MyButton*)button
    {
        [button DSTCount:^(int data_i32) {
            printf("%d ",data_i32);
        }];
    }

    图片补充:

    C回调函数:

    1)、CallBack.C

    2)、CallBack.h

    3)、main.c

    OC的Block

    1)、MyButton.h

    2)、MyButton.m

    3)、RootViewControl.m

    4)、运行

  • 相关阅读:
    BZOJ2648: SJY摆棋子
    BZOJ1925: [Sdoi2010]地精部落
    BZOJ1941: [Sdoi2010]Hide and Seek
    BZOJ2434: [Noi2011]阿狸的打字机
    BZOJ3295: [Cqoi2011]动态逆序对
    BZOJ1406: [AHOI2007]密码箱
    BZOJ1115: [POI2009]石子游戏Kam
    BZOJ1531: [POI2005]Bank notes
    BZOJ2730: [HNOI2012]矿场搭建
    计算几何《简单》入土芝士
  • 原文地址:https://www.cnblogs.com/gh0408/p/6239610.html
Copyright © 2011-2022 走看看