2017-03-06 50 views
0

我的問題如下:我有一個參數類,其中所有參數都有一個parentId,它確實是其他參數的objectId。我想寫一個查詢,在這裏我可以得到所有這些父子關係相互連接的參數列表。所以,我有試過這種..爲什麼變量在循環內部的分析查詢中使用時沒有改變它的值

class ArgumentViewController: UIViewController { 

var all = [String]() 
var temporaryId = "vEKV1xCO09" 

override func viewDidLoad() { 
    super.viewDidLoad() 

    for _ in 1...3 { 
     let query = PFQuery(className: "Argument").whereKey("objectId", equalTo: temporaryId) 

     query.findObjectsInBackground { (objects, error) in 
      if let arguments = objects { 
       for argument in arguments { 
        self.all.append(argument["parentId"] as! String) 
        print(self.all) 
        self.temporaryId = argument["parentId"] as! String 
       } 
      } 
     } 
    } 

}

但問題temporaryId循環內不更新自身。它在所有迭代中都保持不變。因此,當我打印(self.all)我只是得到一個數組的3個字符串,都是我的初始參數的父親

我的目標是獲得一個數組,它是[我的初始參數的父項,我最初的論點,我父母的父母親...]

我已經搜索了類似的主題,但找不到解決方案。任何幫助將非常感激。

+0

所以你的問題是self.temporaryId = argument [「parentId」] as!字符串不會從「vEKV1xCO09」更改爲其他內容是正確的嗎? –

+0

這是完全正確的 –

+1

我想出了爲什麼但仍然找不到解決方案的原因。顯然,由於「findObjectsInBackground」是一個異步查詢,因此主線程在查詢達到結論之前運行。我嘗試使用「findObjects」而不是「findObjectsInBackground」,它給了我正在尋找的數組,但顯着減慢了UI,給我一個「主線程正在執行長時間運行的操作」的警告。 –

回答

0

由於在後臺線程query.findObjectsInBackground運行,沒有辦法更新temporaryId在每一個for環新檢索@"parentId"

所以我想你可以創建一個遞歸函數,是這樣的:

func getParentId() { 
    let query = PFQuery(className: "Argument").whereKey("objectId", equalTo: temporaryId) 

    query.findObjectsInBackground { (objects, error) in 
     if let arguments = objects { 
      for argument in arguments { 
       self.all.append(argument["parentId"] as! String) 
       print(self.all) 
       self.temporaryId = argument["parentId"] as! String 
       while (all.count <= 3) { 
        getParentId() 
       } 
      } 
     } 
    } 
} 

我沒有做過斯威夫特足夠的練習,因爲我一個Objective-C開發人員,所以我很抱歉,如果我犯了一些語法錯誤。

+0

這解決了我的問題。非常感謝你的幫助.. –

相關問題