iOSBlock函式宣告定義以及呼叫等

2021-08-09 07:40:34 字數 2604 閱讀 6358

block函式

/* ---------- block

函式宣告

--------- */

void

(^printconutry_block)(

void);

double

(^getpi_block)();

void

(^printargumentssum_block)(

int,

int,

int);

int(^getsum_block)(

inta,

intb); /*

------------  block

函式定義

-------------- */

void

(^printconutry_block)(

void

) = ^(

void);

double

(^getpi_block)() = ^();

void

(^printargumentssum_block)(

int,

int,

int) = ^(

inta,

intb,

intc);

int(^getsum_block)(

inta,

intb) = ^(

inta,

intb); /*

------ block

函式呼叫

-------- */

printconutry_block

();  

// printmycountry();

printf

("pi=%g\n"

,getpi_block

());  

// getpi();

printargumentssum_block

(10,20,30);  

printf

("sum=%d\n"

,getsum_block

(100,200));

// getmax(33, 44)

(1) block

函式的宣告、定義、呼叫類似於

c函式,但是注意寫法的不同!

(2)  c

函式特點:

可以巢狀呼叫、可以遞迴呼叫、不可以巢狀定義、不可以使用函式名賦值

(3)  block

函式特點:可以巢狀呼叫、可以遞迴呼叫、可以巢狀定義、可以使用函式名賦值

(4)  block

函式的巢狀定義:

int main();

nsstring

*s = blockinnertest(2,

@"china");

nslog

(@"%@"

,s);

return 0; }

(5)假設新的

block

函式的引數、實現都與乙個已有的

block

函式相同,可以使用函式名賦值 /*

block

函式名直接賦值 */

int(^sum)(

int,

int) =

getsum_block;

nslog

(@"sum=%d"

,sum(10,20));

nslog

(@"sum=%d"

,getsum_block

(10,20));

(6)在block

函式體中,只能使用函式體外的區域性變數的值,不可以改變區域性變數的值;

如果想在

block

函式體中對外部區域性變數賦值,方式有3:

<1>

將外部的區域性變數

變成全域性變數

<2>

將區域性變數變為

__block變數(

兩個下劃線)

<3>

將區域性變數變為

static

靜態區域性變數

__block

intinnernum = 200;

dispatch_async

(dispatch_get_global_queue

(0, 0), ^);

(7) 

可以將block

函式做成

oc的屬性

@property

(nonatomic

,strong

)void

(^pass)(

iddata);

函式名就是

oc物件的屬性的名稱,使用如:

self.pass...

(8)可以將block

函式做成乙個型別

,並定義器變數

typedef void(^bloctype)(int,nsstring*); //blocktype

變為乙個型別說明符

blocktype a =^(

intnum,nsstring *str) ;

blocktype a;

blocktype b;

blocktype c; //a , b, c 都是blocktype型別的變數

C 函式的宣告定義

include 宣告 extern char mystrstrpoint char dest,char src extern char mystrstrarr char dest,char src extern char mystrcat char dest,char src extern void...

函式 變數 宣告 定義 呼叫 引用

引例 在高中數學裡,我們有y f x f x 3x 在c語言裡我們有 includeint f int a int main 下面說一下函式的宣告 定義 呼叫 詳見下面 宣告的作用是把函式名 函式引數的個數 函式引數型別等資訊通知編譯系統,以便在遇到函式呼叫時,編譯系統能正確識別函式並檢查呼叫是否合...

c語言 函式宣告定義總結

巢狀呼叫很好理解,就是在乙個子程式裡呼叫另乙個子程式。void print char a void hello 而鏈式訪問就是把乙個函式的返回值直接當作實參傳遞給下乙個函式。int ret strlen strcat hello world 上例中strcat 的返回值是char型別,是目標串的首位...