2016-01-13 36 views
1

我试图在重复循环中运行后台任务(确切地说是query.findobjectinbackground)。赶上是我需要这个完成之前再次运行循环。在循环中继续前进后台任务

我需要它来完成,因为在后台任务中正在填充一个数组,最终会导致UITable被填充。

当我在当前状态下运行它时,循环遍历并在后台任务仍在运行时结束。

这里是我的代码:

//array Im trying to populate 
var contentArray:NSMutableArray = NSMutableArray() 

func queryStatusTable() { 
    contentArray.removeAllObjects() 

    //query my table 
    let queryUser = PFUser.query() 
    let objectIdString = PFUser.currentUser()?.objectId 
    queryUser?.whereKey("objectId", equalTo: objectIdString!) 
    queryUser?.findObjectsInBackgroundWithBlock({ (objects: [PFObject]?, error: NSError?) -> Void in 
     if let objects = objects { 
      for object in objects {      

       //used for the repeat loop 
       //object["userFriendsArray"] is an array I got from my above query 

       var i:Int = 0 
       let count:Int = object["userFriendsArray"].count 

       repeat { 

        //second query 
        let queryFriendStatus = PFQuery(className: "Content") 
        queryFriendStatus.whereKey("userObjectId", equalTo: object["userFriendsArray"][i]) 

        //this is what I want to finish before the loop moves on 
        queryFriendStatus.findObjectsInBackgroundWithBlock({ (objects: [PFObject]?, error: NSError?) -> Void in 
         if let objects = objects { 
          for object in objects { 
           self.contentArray.addObject(object["content"]) 
          } 
         } 

        }) 

        //so i dont want this to run until the above task finishes 
        //and putting this inside the above task doesnt work because it will never run if its inside the findobjectinbackground 
        i++ 

       } while (i < count) 
      } 
     } 

     //this is where I reload the table data to populate it with 
     //whats in my *contentArray* 
     self.firstTableView.reloadData() 
    }) 
} 

那么我将如何确保contentArray之前self.firstTableView.reloadData()运行填充?

任何帮助将被认可,谢谢!

回答

0

为什么不在建立数据时定期更新表格?

它会给用户一些东西看,并会出现更快。

我已经通过调用重载这样做之前每50行(或其他),然后在最后,再次调用它来获得最后行

记住通过主队列从内打的电话你的背景数据收集 - 像这样

dispatch_async(dispatch_get_main_queue()) { 
    self.firstTableView.reloadData() 
} 
+0

你一次加载一行很好,但即使我改变它也不会有帮助。在我的代码中,* self.firstTableView.reloadData()*在我的数组被填充之前被调用,所以我需要弄清楚如何在数组填充后调用* self.firstTableView.reloadData()*。这是我遇到的麻烦。 –

+0

前提是您设置的行数与您已加载的数据量相匹配,然后您可以对self.firstTableView.reloadData()进行重复调用,并且您将看到该表正在填充,而其余数据已加载。所有你需要的是提醒用户一切都完成的方式 - 或者是一个ActivityIndi​​cator,或者最后一条消息。 您可能不想更新每一行 - 这只会减慢速度,但您可以一次更新一两页 – Russell

+0

您对第一个reloadData有所了解 - 不会有任何数据准备就绪对于那个 - 但你不需要它,如果你在刷新整个负载 - 并且最后再一次,除非你有一个确切倍数的刷新间隔! – Russell