block 應用說明,block應用
一、Block定義
Block可以理解為一個函數指標(即它是一個指標,指向某個函數)
returnType (^blockName) (parameter list) = ^ (parameter list) {代碼塊};
說明:
returnType:block的傳回型別,可定義為void;
blockName:block的命名,可根據不同的變數/函數命名規範進行命名;
parameter list:block形參類型定義,可傳入多個值,也可沒有參數;
舉例說明:
//定義無參無傳回值的Block
void (^printBlock)() = ^(){
printf("no number");
};
printBlock();
void (^myBlock)(NSString *); //block 聲明
- (void)viewDidLoad
{
//block 在代碼中的實現
myBlock = ^(NSString *text){
NSLog(@"my text = %@", text);
};
//調用block函數的實現
int nCount = myCount(10, 5);
NSLog(@"count = %zi", nCount);
}
//block函數原型定義
int (^myCount)(int a, int b) = ^(int a, int b)
{
return a+b;
};
二、Block作為函數參數傳遞
returnType (^blockName) (parameter list)
說明:
returnType:block的傳回型別,可定義為void;
blockName:block的命名,可根據不同的變數/函數命名規範進行命名;
parameter list:block形參類型定義,可傳入多個值,也可沒有參數;
實際聲明方式:
+ (void)updateImage:(void(^)(NSInteger status,NSDictionary *res))block;
//變更網路請求方式
-(void)ModifyRequestMode:(void(^)())block
{
//取消所有任務,放到全域隊列中優先順序最高
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
ZLBAFHTTPClient *httpClient = [ZLBAFHTTPClient shareClient];
//取消隊列中的所有網路請求任務
[httpClient cancelAllTasks];
//取消隊列中所有任務
[httpClient.workQueue cancelAllOperations];
//重新匹配正確的CDN節點
[[ZLBGlobal sharedGlobal] changeNetwork:^{
block();
}];
});
}
- (RACDisposable *)subscribeNext:(void (^)(id x))nextBlock completed:(void (^)(void))completedBlock {
NSCParameterAssert(nextBlock != NULL);
NSCParameterAssert(completedBlock != NULL);
RACSubscriber *o = [RACSubscriber subscriberWithNext:nextBlock error:NULL completed:completedBlock];
return [self subscribe:o];
}