2014-09-03 39 views
1

對此併發性有困難,最後我試圖按照請求的順序將異步獲取對象添加到數組中,即第一次獲取應該添加到數組[0],第二次獲取應該添加到數組[1]等等。問題是,到獲取完成時,我的索引計數已經改變了,我怎樣才能將索引計數傳遞給異步塊,所以它使用正確的?如何使用Swift在異步完成塊中的特定索引處將數據添加到數組中

class BATableViewController: UITableViewController { 
    var paymentArray = [[AnyObject]]() 
    var keepCount = 0 


func buildPaymentsArray(expenses: Array<AnyObject>!){ 
    for (index, expense) in enumerate(expenses) { 
     // query for all Payments for that expense 
     var paymentQuery = PFQuery(className: "Payment") 
     paymentQuery.whereKey("expense", equalTo: expense) 
     paymentQuery.findObjectsInBackgroundWithBlock({ (objects: [AnyObject]!, error: NSError!) -> Void in 
      self.paymentArray[self.keepCount] = objects 
      self.keepCount++ 
     }) 
    } 
} 

回答

4

只是預擴展你的陣列,以及要將其插入他們:

func buildPaymentsArray(expenses: Array<AnyObject>!){ 
    // Pre-allocate your array. (This *really* shouldn't be AnyObject if you can at all help it) 
    self.paymentArray = [[AnyObject]](count: expenses.count repeatedValue: []) 

    for (index, expense) in enumerate(expenses) { 
     // query for all Payments for that expense 
     var paymentQuery = PFQuery(className: "Payment") 
     paymentQuery.whereKey("expense", equalTo: expense) 
     paymentQuery.findObjectsInBackgroundWithBlock({ (objects: [AnyObject]!, error: NSError!) -> Void in 
      self.paymentArray[index] = objects // <=== write it to the index location from expenses 
      self.keepCount++ // <== I assume you shouldn't need this 
     }) 
    } 
} 
+0

謝謝!解析返回並設置他們與AnyObject的獲取,但我同意我想有更多的類型。這工作很好,我發誓我曾嘗試過使用索引 – yoshyosh 2014-09-03 18:41:09

相關問題