解决网络请求的依赖关系
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                解决网络请求的依赖关系
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.                        
                                ?
怎么解決網(wǎng)絡請求的依賴關系:當一個接口的請求需要依賴于另一個網(wǎng)絡請求的結果
-  
思路1:操作依賴:NSOperation 操作依賴和優(yōu)先級(不適用,異步網(wǎng)絡請求并不是立刻返回,無法保證回調時再開啟下一個網(wǎng)絡請求)
 
| 1 | [operationB?addDependency:operationA];?//?操作B依賴于操作 | 
-  
思路2:邏輯判斷:在上一個網(wǎng)絡請求的響應回調中進行下一網(wǎng)絡請求的激活(不適用,可能拿不到回調)
 -  
思路3:線程同步 -- 組隊列(dispatch_group)
 
| 1 2 3 4 5 6 7 8 | dispatch_queue_t?queue?=?dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,?0); dispatch_group_t?group?=?dispatch_group_create(); dispatch_group_async(group,?queue,?^{?/*加載圖片1?*/?}); dispatch_group_async(group,?queue,?^{?/*加載圖片2?*/?}); dispatch_group_async(group,?queue,?^{?/*加載圖片3?*/?});? dispatch_group_notify(group,?dispatch_get_main_queue(),?^{ ????????//?合并圖片…?… }); | 
-  
思路4:線程同步 --阻塞任務(dispatch_barrier):
 
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | /*?創(chuàng)建并發(fā)隊列?*/ dispatch_queue_t?concurrentQueue?=?dispatch_queue_create("test.concurrent.queue",?DISPATCH_QUEUE_CONCURRENT); /*?添加兩個并發(fā)操作A和B,即A和B會并發(fā)執(zhí)行?*/ dispatch_async(concurrentQueue,?^(){ ????NSLog(@"OperationA"); }); dispatch_async(concurrentQueue,?^(){ ????NSLog(@"OperationB"); }); /*?添加barrier障礙操作,會等待前面的并發(fā)操作結束,并暫時阻塞后面的并發(fā)操作直到其完成?*/ dispatch_barrier_async(concurrentQueue,?^(){ ????NSLog(@"OperationBarrier!"); }); /*?繼續(xù)添加并發(fā)操作C和D,要等待barrier障礙操作結束才能開始?*/ dispatch_async(concurrentQueue,?^(){ ????NSLog(@"OperationC"); }); dispatch_async(concurrentQueue,?^(){ ????NSLog(@"OperationD"); }); | 
-  
思路5:線程同步 -- 信號量機制(dispatch_semaphore):
 
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | /*?創(chuàng)建一個信號量?*/ dispatch_semaphore_t?semaphore?=?dispatch_semaphore_create(0); /*?任務1?*/ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,?0),?^{ ????/*?耗時任務1?*/ ????NSLog(@"任務1開始"); ????[NSThread?sleepForTimeInterval:3]; ????NSLog(@"任務1結束"); ????/*?任務1結束,發(fā)送信號告訴任務2可以開始了?*/ ????dispatch_semaphore_signal(semaphore); }); /*?任務2?*/ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,?0),?^{ ????/*?等待任務1結束獲得信號量,?無限等待?*/ ????dispatch_semaphore_wait(semaphore,?DISPATCH_TIME_FOREVER); ????/*?如果獲得信號量則開始任務2?*/ ????NSLog(@"任務2開始"); ????[NSThread?sleepForTimeInterval:3]; ????NSLog(@"任務2結束"); }); [NSThread?sleepForTimeInterval:10]; | 
轉載于:https://www.cnblogs.com/ruixin-jia/p/9475997.html
總結
以上是生活随笔為你收集整理的解决网络请求的依赖关系的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: mybatis generator 属性
 - 下一篇: sql 指定数据库中的信息操作