前言
有时候在调用多个模块时,会对同一个API进行多次请求,但因为内容都是一样的,所以最好就是加上锁,防止重复请求造成网络资源浪费
处理方法
@synchronized (self) {//加锁,避免数组重复创建添加等问题 static NSMutableArray * successBlocks;//用数组保存回调 static NSMutableArray * failureBlocks; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{//仅创建一次数组 successBlocks = [NSMutableArray new]; failureBlocks = [NSMutableArray new]; }); if (success) {//每调用一次此函数,就把回调加进数组中 [successBlocks addObject:success]; } if (failure) { [failureBlocks addObject:failure]; } static BOOL isProcessing = NO; if (isProcessing == YES) {//如果已经在请求了,就不再发出新的请求 return; } isProcessing = YES; [self callerPostTransactionId:transactionId parameters:dic showActivityIndicator:showActivityIndicator showErrorAlterView:showErrorAlterView success:^(id responseObject) { @synchronized (self) {//网络请求的回调也要加锁,这里是另一个线程了 for (successBlock eachSuccess in successBlocks) { //遍历回调数组,把结果发给每个调用者 eachSuccess(responseObject); } [successBlocks removeAllObjects]; [failureBlocks removeAllObjects]; isProcessing = NO; } } failure:^(id data) { @synchronized (self) { for (failureBlock eachFailure in failureBlocks) { eachFailure(data); } [successBlocks removeAllObjects]; [failureBlocks removeAllObjects]; isProcessing = NO; } }]; }