值从关闭开始重新初始化

时间:2018-10-03 09:46:09

标签: ios swift firebase asynchronous

我创建了一个对象数组playerArray来存储播放器的数据,然后通过ref调用firebase数据库。在闭包中,我确实从firebase中获取了值并将其分配给属性.name,但是在闭包中,该值被重新初始化为初始值。

var playerArray:[model] = [model]()

let ref = Database.database().reference().child("Players").child("Ronaldo")


func read(){

    ref.observe(.value) { (snap) in
        var val = snap.value as! Dictionary<String,AnyObject>
        let name = val["Name"] as! String
        let Model = model()
        Model.name = name
        self.playerArray.append(Model)
        print(snap)
    }

} 
 override func viewDidLoad() {
    super.viewDidLoad()
    read()
    table.delegate = self
    table.dataSource = self
    table.reloadData()
}

3 个答案:

答案 0 :(得分:1)

更改参数后,应重新加载表。在viewDidLoad()中,它只会发生一次。

答案 1 :(得分:0)

问题在于,您无法在read中异步检索到数据后不会重新加载表视图。您只需要从reloadData的完成处理程序内部调用observe

ref.observe(.value) { (snap) in
    var val = snap.value as! Dictionary<String,AnyObject>
    let name = val["Name"] as! String
    let Model = model()
    Model.name = name
    self.playerArray.append(Model)
    DispatchQueue.main.async {
        self.table.reloadData()
    }
}

也无需在reloadData中致电viewDidLoad

答案 2 :(得分:0)

在闭包主体中附加playerArray之后,您应该刷新tableview

override func viewDidLoad() {
    super.viewDidLoad()
    table.delegate = self
    table.dataSource = self
    read()
}


func read(){

    ref.observe(.value) { (snap) in
        var val = snap.value as! Dictionary<String,AnyObject>
        let name = val["Name"] as! String
        let Model = model()
        Model.name = name
        self.playerArray.append(Model)
        print(snap)
        self.table.reloadData()

    }

}