2016-05-12 78 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