全局变量似乎失去价值(迅速)

时间:2017-07-08 08:02:45

标签: swift

这是我从firebase中提取数据的代码 listofnames(二维)和名称(一维)是String类型的全局数组。

但是,当我打印listofnames时,输出窗口中会显示一个空数组,而如果我注释第一行(self.listofnames = [[]]),代码就会正常运行。

我已将ref与Firebase数据库

相关联

请帮忙。

var databasehandle:FIRDatabaseHandle?

let time = ["8AM - 9AM", "9AM - 10AM","10AM - 11AM", "11AM -12PM", "12PM - 1PM","1PM - 1:30PM","2PM - 3PM","3PM - 4PM","4PM - 5PM","5PM - 6PM","6PM - 7PM","7PM - 7:30PM"]

var ref:FIRDatabaseReference!
var day: String = "Monday"
var users :String = "First years"

func loaddata()
{
    self.listofnames = [[]]
    for x in 0...((time.count)-1)
    {
        ref.child(users).child(day).child(time[x]).observeSingleEvent(of: .value, with: {(snapshot) -> Void in
            if let namesfromFirebase = snapshot.value as? [String:Any]
            {
                let y = namesfromFirebase.count
                for i in 1...y
                {
                    self.names.append(namesfromFirebase["s"+"\(i)"] as! String)
                }
            }
            self.listofnames.append(self.names)
            self.names = []
        })
    }
    print(self.listofnames)
    self.tableView.reloadData()
}

1 个答案:

答案 0 :(得分:0)

observeSingleEvent异步工作,后面会调用闭包。

有一个简单的解决方案:将两行移动到闭包中:

func loaddata()
{
    self.listofnames = [[]]
    for x in 0..<time.count // no parentheses and math needed when using `..<`
    {
        ref.child(users).child(day).child(time[x]).observeSingleEvent(of: .value, with: {(snapshot) -> Void in
                if let namesfromFirebase = snapshot.value as? [String:Any]
                {
                    let y = namesfromFirebase.count
                    for i in 1...y
                    {
                        self.names.append(namesfromFirebase["s"+"\(i)"] as! String)
                    }
                }
                self.listofnames.append(self.names)
                self.names = []
                print(self.listofnames)
                self.tableView.reloadData()
        })
    }
}