gpt4 book ai didi

ios - Firebase:iOS:Firebase 读取后数组变空

转载 作者:行者123 更新时间:2023-11-28 14:48:06 24 4
gpt4 key购买 nike

我正在使用存储在结构中的数组来存储来自 firebase 数据库的条目。我可以成功加载数据,因为我可以打印出数据库的每个项目。然而,一个名为 allMovies 的数组在某种程度上是空的,即使我只是用来自 firebase 的数据填充它。

为什么会这样?

这是我的代码:

保存我的数组的全局结构及其更改在整个程序中都是可见的。

struct GlobalMovies {
static var allMovies:[Movies] = []
static var hotMovies:[Movies] = []
static var upcomingMovies:[Movies] = []
}

从我的 firebase 读取数据的功能。如前所述,我能够成功读取数据。

var ref:DatabaseReference?
var databaseHandle:DatabaseHandle?

databaseHandle = ref?.child("Movies").observe(.childAdded, with: { (snapshot) in
if let userDict = snapshot.value as? [String:Any] {

GlobalMovies.allMovies.append(Movies(name: userDict["name"]! as! String ,
rating: userDict["rating"]! as! String,
length: userDict["length"]! as! String,
genre: userDict["genre"]! as! String ,
cast : userDict["cast"] as! [String],
cinemas : userDict["cinemas"] as! [String],
releaseDate: userDict["releaseDate"]! as! String,
director: userDict["director"]! as! String,
description: userDict["description"]! as! String ,
image: userDict["image"]! as! String,
isHot: userDict["isHot"]! as! Bool,
isUpcoming: userDict["isUpcoming"]! as! Bool))
self.table.reloadData()


}
})
print(GlobalMovies.allMovies.count) //prints out 0 when it shouldn't

我的 json 文件:

{
"Movies": {
"Movie1" : {
"name": "The Incredible Hulk",
"rating": "4/5",
"length": "120 minutes",
"genre": "Fantasy",
"cast" : ["Lisa Simpson", "Peter Griffin"],
"cinemas": ["A", "B"],
"releaseDate": "12/05/2018",
"director": "Mike Lancaster",
"description" : "Lorem Ipsum",
"image": "default",
"isHot": true,
"isUpcoming": false
},
"Movie2" : {
"name": "Star Wars",
"rating": "5/5",
"length": "120 minutes",
"genre": "SciFi",
"cast" : ["Lisa Simpson", "Peter Griffin"],
"cinemas": ["A", "B"],
"releaseDate": "12/05/2018",
"director": "Mike Lancaster",
"description" : "Lorem Ipsum",
"image": "default",
"isHot": true,
"isUpcoming": false
}


}
}

最佳答案

原因是因为 firebase 异步获取数据,所以当您进行打印时它还没有获取数据,但一段时间后它会获取它们。你要做的就是在获取完成后打印数据

关于ios - Firebase:iOS:Firebase 读取后数组变空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50084376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com