iOS 如何解决并发请求时,只接受最后一个请求返回的结果

 
大致意思是 虽然NSOperation 的cancel 并不能取消请求,但是可以对这个NSOperation进行标记。
当cancel 属性是YES时,表明 NSOperation虽然已经执行,并返回了结果,但是我现在不需要了。那么我们每次执行request的时候都把上一个operation cancel掉,然后在completion  Block中判断operation是否cancel,如果cancel那么不返回response的值。
 
 1 + (AFHTTPRequestOperation *)requestSellerWithCompletion:(requestFinishedCompletionBlock)successBlock
 2 {
 3     AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
 4 
 5     AFHTTPRequestOperation * operation = [manager GET:kRequestSellerURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
 6  
 7         if (operation.isCancelled) {
 8          //若果operation已经被cancel了,则不对返回数据进行处理
 9             NSLog(@"operation is Canceled");
10         }else{
11      //如果没有cancel 掉,则进行正常的数据解析
12             NSArray *sellerArray = [MTLJSONAdapter modelsOfClass:[Seller class] fromJSONArray:responseObject[@"data"] error:nil];
13             if (successBlock) {
14               //  NSLog(@"current operation count is %d",[manager.operationQueue operations].count);
15                 successBlock(sellerArray);
16             }
17         }
18 
19 
20     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
21 
22     }];
 
 
 
然后在for循环里这么做.

for (int i = 1; i <= 10; i++) {

        if (operation) {
            [operation cancel];
        }
      operation = [Seller requestSellerWithCompletion:^(id object) {
            NSLog(@"finished download %d",i);

        }];

    }
 

运行一下看看console .

 
 
看到叶孤城的一篇文章,现在自己总结如上
 
 
 
原文地址:https://www.cnblogs.com/ljlkfx/p/4821853.html