iOS 如何解決並發請求時,只接受最後一個請求返回的結果,ios最後一個

來源:互聯網
上載者:User

iOS 如何解決並發請求時,只接受最後一個請求返回的結果,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 .

  看到葉孤城的一篇文章,現在自己總結如上   

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.