嵌入式&iOS:回呼函數(C)與block(OC)傳 參/函數 對比

來源:互聯網
上載者:User

標籤:分享   div   嵌入式   sid   需要   gre   png   typedef   ram   

C的回呼函數:

callBack.h

1)、聲明一個doSomeThingCount函數,參數為一個(無傳回值,1個int參數的)函數。

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

 

callBack.c

1)、在doSomeThingCount函數,對運行次數自增,並調用參數--函數。

void DSTCount(void(*CallBack)(int data_i32)){    static int numb = 0;    numb++;    (*CallBack)(numb);}

 

main.c

1)、定義一個customdoSomeThingCount函數,列印資料。

void customDSTCount(int data_i32){    printf("%d\n",data_i32);}

2)、main函數裡,運行 callBack.h 的 DSTCount 函數,參數為main裡的customDSTCount函數。

while (1){    DSTCount(customDSTCount);}

 

 

 

OC的Block:

MyButton.h(繼承於UIButton):

1)、定義一個Block的參數數量、類型。

typedef void(^ButtonBlock)(int data_i32);

2)、聲明一個doSomeThingCount函數,帶Block參數。(注意,這裡不需要加*,類用習慣了,參數隨手就加個*)

-(void)DSTCount:(ButtonBlock)myButtonBlockPTR;

 

MyButton.m(繼承於UIButton):

1)、在doSomeThingCount函數,對運行次數自增,並調用Block參數。

-(void)DSTCount:(ButtonBlock)myButtonBlockPTR{    static int numb = 0;    numb++;    myButtonBlockPTR(numb);}

 

RootViewControl.m(self.window.rootViewController):

1)、viewDidLoad函數,定義一個(100,100,100,100)、紅色的按鈕執行個體,按鈕添加事件,把按鈕加到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)、按鈕點擊調用,調用MyButton裡的DSTCount函數,Block參數直接輸入。

-(void)mybuttonClick:(MyButton*)button{    [button DSTCount:^(int data_i32) {        printf("%d\n",data_i32);    }];}

 

 

 

 

 

 

圖片補充:

C回呼函數:

1)、CallBack.C

2)、CallBack.h

3)、main.c

 

 

 

OC的Block

1)、MyButton.h

2)、MyButton.m

3)、RootViewControl.m

4)、運行

嵌入式&iOS:回呼函數(C)與block(OC)傳 參/函數 對比

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.