【发布时间】:2021-02-18 10:47:48
【问题描述】:
我正在尝试从 Firestore 数据库中获取数据,如下所示:
texts - 1 - message (String)
author (String)
- 2 - message (String)
author (String)
...
出于测试目的,我将消息字符串设置为“test”+它们包含的数字(例如 1 将是 test1)
我用来在堆栈视图中将这些显示为标签的代码是:
if startNumOfMessages > 0 {
let g = DispatchGroup()
for message in stride(from: startNumOfMessages, through: 1, by: -1) {
g.enter()
print(message)
db.collection("chats").document(self.userDefaults.string(forKey: "currentGroup")!).collection("texts").document("\(message)").getDocument { (doc, err) in
if err != nil{
print("Error getting message \(message)")
}
else{
if doc!.exists{
let messData = doc!.data()
messageArray.append(messData!["message"] as! String)
authorArray.append(messData!["author"] as! String)
}
else{
print("Document Doesnt exist")
}
}
g.leave()
}
}
//Display them
g.notify(queue: .main){
print(messageArray)
for num in stride(from: messageArray.count - 1, through: 0, by: -1){
let authorLabel = UILabel()
authorLabel.text = authorArray[num]
authorLabel.font = UIFont(name:"SF Pro", size: 10.0)
authorLabel.textColor = UIColor.lightGray
self.stackView.addArrangedSubview(authorLabel)
let label = UILabel()
label.text = messageArray[num]
self.stackView.addArrangedSubview(label)
}
}
}
但是,当我 print(messageArray) 时,数组显示为
["test1", "test3", "test2", "test4", "test5"]
所以我的问题是为什么会发生这种情况?我试过弄乱循环,但它们看起来很好,我检查了它获取的数据,那里没有任何不正确的地方。
【问题讨论】:
-
如果您在
getDocument的闭包中打印消息并将它们附加到数组中,它们的顺序是否正确? Order and limit data 的文档说:默认情况下,查询会按文档 ID 升序检索满足查询的所有文档,您需要使用order(by:,来实际对数据进行排序。 -
它们的顺序不正确,这让我感到困惑,它与最终数组的顺序相同,这意味着什么吗?
-
但是它们每次都以同样的混乱顺序出现