2016-05-12 95 views
1

我有一個網絡服務,它根據categoryID回報我的新聞。我想加載與所有新聞相關的新聞。什麼是最有效的方法來做到這一點?我正在使用swift。我正在這樣做。快速有效的數據加載

`

for(i=0 ; i<cat.count ;i++) 
{ 

self.loadCat(cat[i]["catID"]) 
} 

然後在我的載荷種類方法IM檢查當前ID和內容加載到單獨的陣列

`

func loadCat(String:id) 
{ 
    serviceCall() 
if id==1 
{ 
    self.news.append(currentArray) 
} 
else if id==2 
{ 
    self.sports.append(currentArray) 
} 

else is id==3 
{ 
    self.world.append(currentArray) 
    } 

需要很長的時間來加載所有數據當我有10個類別時,進入單獨的數組。我怎樣才能讓這個更快。請幫幫我。 感謝

+0

用例替換如果,否則如果 –

回答

1

您可以使用GCD併發請求:

dispatch_async(dispatch_queue_create("com.you.downloadCats", DISPATCH_QUEUE_CONCURRENT)) { 
    // add your request here, don't forget to dispatch to main queue 
} 
+0

什麼是這個com.you.downloadCats? – user1960169

+0

@ user1960169它只是一個標識符。 – Lumialxk

0

你也可以改變你的代碼,

把每一個類別爲對象的數組。比方說,這是

var categories = [Category]().  //news,sports,world 

然後,在你的循環變化

self.loadCat(cat[i]["catID"]) 

self.loadCat(cat[i])

func loadCat(Category:category){ 
categories[category] += currentArray 
} 
0

不知道,如果你的數據在一個特定的順序下載,但你可以嘗試這種方式,如果你不需要它爲了

let sema = dispatch_semaphore_create(2); //depending how many downloads you want to go at once 
    for i in 0..<cat.count { 
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { 

      dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER); 

      //download here, order of execution will not be guaranteed 
      self.loadCat(cat[i]["catID"]) //maybe pass i as a parameter inside so you know which element of the for loop your are dealing with 

      dispatch_semaphore_signal(sema); 
     }) 
    } 

如果你改變你的loadCats的工作方式,你可以保存命令

+0

謝謝你能解釋我這一行嗎?讓sema = dispatch_semaphore_create(2); – user1960169

+0

循環內部的信號量是多少? – vadian

+0

我只得到最後一個數組填充。其他2個陣列變空 – user1960169