2016-01-13 87 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