2017-08-11 100 views
-2

我一直在爲這一整天奮鬥,它似乎沒有任何意義,因爲我有非常相似的代碼工作正常。我試過了所有的東西,我試着做一個單獨的方法來返回一個字符串數組,但沒有一個工作。每次,當在括號之後訪問括號(在讀取「print(self.postIDs)」的行後面)時,postIDs數組被設置爲null。感謝您給我提供的任何幫助。因swift中的for循環而無法修改數組?

var postIDs = [String]() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    tableView.dataSource = self 
    tableView.delegate = self   

    let ref = Database.database().reference() 
    let uid = Auth.auth().currentUser!.uid 

    ref.child("users").child(uid).child("saved").observeSingleEvent(of: .value, with: { snapshot in 
     var ids = [String]() 

     let saved = snapshot.value as! [String:AnyObject] 
     for (elem, _) in saved { 
      ids.append(elem) 
     } 
     self.postIDs = ids 
     print(self.postIDs) // returns the values I would expect 
    }) 
    ref.removeAllObservers() 

    guard self.postIDs.count >= 1 else {return} // postIDs count is equal to 0 here, and when I print postIDs the result is [] 
+0

的原因是塊'observeSingleEvent'中的代碼與你的其他函數不在同一個線程中。其餘的在主線程中,而'observeSingleEvent'在後臺運行。它們是異步的。您的數據完成加載後,您需要獲取'postIDs'。 – Lawliet

+0

您得到期望值的聲明在閉包中。這會導致關閉塊的延遲執行。你可以嘗試檢查一個完成處理程序是否可以被執行,否則你應該在關閉本身內使用數組完成所需的東西。 – Rishabh

+0

在block'observeSingleEvent'內部和外部放置斷點,您將看到區別。 – Lawliet

回答

0

這是因爲背景和其它代碼的行

ref.child("users").child(uid).child("saved").observeSingleEvent(of: .value, with: { snapshot in 
    var ids = [String]() 

    let saved = snapshot.value as! [String:AnyObject] 
    for (elem, _) in saved { 
     ids.append(elem) 
    } 
    self.postIDs = ids 
    print(self.postIDs) // returns the values I would expect 
}) 

工程執行前的回調來

0

檢查下面的代碼

override func viewDidLoad() { 

     super.viewDidLoad() 
     usersTableView.dataSource = self 
     usersTableView.delegate = self 
//  getSnapShot() 


     let databaseRef = Database.database().reference() 

     databaseRef.child("Users").observe(.value, with: { (snapshot) in 

      if snapshot.exists() { 
       self.postData = snapshot.value! as! [String : AnyObject] 
       self.postData.removeValue(forKey: self.appDelegate.KeyValue) 
//    self.getUserNames(Snapshot: self.postData) 
      } 
      else{ 
       print("No users") 
      } 
      print(self.postData) //Does not return nil 
      self.getSnapShot() //Take snapshot outside paranthesis 
     }) 

     print(self.postData) //Returns nil 
    } 


    func getSnapShot() { 

     print(self.postData) //Value of Snapshot is printed 

    } 
+0

非常感謝您的快速響應,我現在嘗試實施。 – Matt

+0

是的,請讓我知道如果你仍然面臨問題 –

+0

它的工作? –