標籤:style tar ext int c strong
1.定義Block
/* 回傳void ,參數也是void 的block*/
void (^blockReturningVoidWithVoidArgument)( void );
/* 回傳整數,兩個參數分別是整數和字元型態的block*/
int (^blockReturningIntWithIntAndCharArguments)( int , char );
/* 回傳void ,含有10 個block 的陣列,每個block 都有一個型態為整數的參數*/
void (^arrayOfTenBlocksReturningVoidWinIntArgument[ 10 ])( int );
/* 定義對象方法使用block,block中需要傳入一個NSString參數,返回void*/
- (void)testBlockWithParam:(void (^)(NSString *text))block;
2.使用Block
- (void)testBlockWithParam:(void (^)(NSString *text))block{
NSLog(@"start test");
// 定義參數x,在testx中使用
int x = 1;
int (^testx)(int) = ^(int num2){
return x+num2;
};
NSLog(@"use x:%d",testx(12));
// 使用__block標示符,定義一個可在block中修改值的參數y
__block int y = 2;
int (^testy)(int) = ^(int num2){
if (num2 > 10) {
y = 10;
}else{
y = 2;
}
return y+num2;
};
NSLog(@"when num2 > 10,sum = %d",testy(20));
NSLog(@"when num2 <= 10,sum = %d",testy(8));
[NSThreadsleepForTimeInterval:1.0f];
block(@"success");
}