前言:定義Block時(shí)侦副,可以對(duì)Block的輸入?yún)?shù)以及返回值的類型進(jìn)行定義侦锯。可以有輸入?yún)?shù)秦驯,也可以沒有輸入?yún)?shù)率触;可以設(shè)置一個(gè)輸入?yún)?shù),也可以設(shè)置多個(gè)參數(shù);可以有返回值葱蝗,也可以沒有返回值。
1细燎、無輸入?yún)?shù)+無返回值
這種形式的Block两曼,無需任何輸入?yún)?shù),并且無返回值玻驻,一般都是在該Block中完成一些動(dòng)作悼凑,例如在完成一段動(dòng)畫后,執(zhí)行一段Block璧瞬,如下所示:
@interfaceUIView(UIViewAnimationWithBlocks)
+(void)animateWithDuration:(NSTimeInterval)duration animations:(void(^)(void))animations;
我們也可以自定義一個(gè)無輸入?yún)?shù)户辫、無返回值的Block,如下所示:
void(^blockWithOutInputAndOutput)(void)=^(void){
NSLog(@"block Called!");
};
2嗤锉、有輸入?yún)?shù)+無返回值
這種形式的Block渔欢,有輸入?yún)?shù),但無返回值瘟忱。一般都是在該Block中根據(jù)輸入?yún)?shù)完成一些動(dòng)作奥额,例如,在AFNetworking中访诱,當(dāng)獲取到網(wǎng)絡(luò)反饋的數(shù)據(jù)后垫挨,會(huì)調(diào)用一個(gè)Block,并且把從服務(wù)器獲取的數(shù)據(jù)作為參數(shù)触菜,傳入Block九榔。
-(AFHTTPRequestOperation*)POST:(NSString*)URLString
parameters:(id)parameters
success:(void(^)(AFHTTPRequestOperation*operation,id responseObject))success
failure:(void(^)(AFHTTPRequestOperation*operation,NSError*error))failure
{
AFHTTPRequestOperation*operation=[selfHTTPRequestOperationWithHTTPMethod:@"POST"URLString:URLStringparameters:parameters success:success failure:failure];
[self.operationQueue addOperation:operation];
returnoperation;
}
我們也可以自定義一個(gè)有輸入?yún)?shù)、無返回值的Block涡相,如下所示:
void(^blockWithInput)(int)=^(intinputNum){
NSLog(@"blockWithInput Called!");
};
3哲泊、有輸入?yún)?shù)+有返回值
Block定義
int(^blockWithOutputAndInput)(int)=^(intinputNum){
NSLog(@"blockWithOutputAndInput Called!");
returninputNum;
};
Block調(diào)用
intintNumber2=blockWithOutputAndInput(200);
NSLog(@"blockWithOutputAndInput:%d",intNumber2);
4、有多個(gè)輸入?yún)?shù)
可以在Block定義中傳入多個(gè)參數(shù)漾峡。
Block的定義
double(^multiplyTwoValues)(double,double)=^(doublenumber1,doublenumber2){
returnnumber1*number2;
};
Block的調(diào)用
doubledoubleNumber=multiplyTwoValues(5.0,5.6);
NSLog(@"multiplyTwoValues: %f",doubleNumber);
5攻旦、無輸入?yún)?shù)+有返回值
Block的定義
int(^blockWithOutput)(void)=^(void){
NSLog(@"blockWithOutput Called!");
return100;
};
Block的調(diào)用
intintNumber1=blockWithOutput();
NSLog(@"blockWithOutput:%d",intNumber1);