gpt4 book ai didi

swift 火力地堡 : loop through data and only start the new loop if the old one has finished loading

转载 作者:行者123 更新时间:2023-11-30 11:43:20 24 4
gpt4 key购买 nike

我遇到了麻烦,因为我正在以用户的形式加载大量数据条目(大约 1000 个)。现在,我获取用户的 userID,并将其包含用户数据的行插入到我的 TableView 中。问题是,目前我的应用程序会等待,直到完成所有用户 ID 的检查,然后才开始插入它们。代码如下:

let group = DispatchGroup()

for each in userIDs {

check(identifier: "DispatchGroup", text: "\(each) started")

Database.database().reference().child("user-data").child(each).observeSingleEvent(of: .value, with: { (snap) in

if let data = snap.value as? [String:AnyObject] {

if let name = data["name"] as? String, let urlToImage = data["imagePath"] as? String, let status = data["status"] as? String {

let newUser = User()
newUser.name = name
newUser.imagePath = urlToImage
newUser.status = status

self.usersTableView.append()

if let index = self.usersTableView.index(of: newUser) {
self.tableView.insertItems(at: [IndexPath(row: index, section: 0)])
check(identifier: "FeedLoad", text: "inserting user \(newUser.userName) at timestamp \(Date().timeIntervalSince1970)")
}

check(identifier: "DispatchGroup", text: "\(each) ended")

print("Reloading table view at \(Date().timeIntervalSince1970)")

group.leave()

}

}

})



}

现在,打印出来的是:

调度组:xRDlUIBAsqeI13ykVsEx9P7okph2 已启动

调度组:dFVZAQmPb0TRRD94sPR32FbYWyk1 已启动

调度组:xRDlUIBAsqeI13ykVsEx9P7okph2 已结束

调度组:dFVZAQmPb0TRRD94sPR32FbYWyk1 已结束

但我想说:

调度组:xRDlUIBAsqeI13ykVsEx9P7okph2 已启动

调度组:xRDlUIBAsqeI13ykVsEx9P7okph2 已结束

调度组:dFVZAQmPb0TRRD94sPR32FbYWyk1 已启动

调度组:dFVZAQmPb0TRRD94sPR32FbYWyk1 已结束

如何实现这一目标?

最佳答案

有几种方法可以实现这一目标。 Firebase 没有针对此类内容的完成处理程序,但是如果 for 循环中有少量 ID,您可以做的就是像这样嵌套它:

Database.database().reference().child("user-data").child(id1).observeSingleEvent(of: .value, with: { (snap) in
Database.database().reference().child("user-data").child(id2).observeSingleEvent(of: .value, with: { (snap) in
Database.database().reference().child("user-data").child(id3).observeSingleEvent(of: .value, with: { (snap) in

}
}
}

但是,如果该数据可能会发生变化,则实现此目的的另一种方法是存储 ids 和 Bool 的字典以检查是否完成。

var ids = ["id1" : false, "id2" : false, "id3" : false]

func getNext() {
// If all ids == true { return }
// if not, get the next id

Database.database().reference().child("user-data").child(id1).observeSingleEvent(of: .value, with: { (snap) in
ids["id1"] = true
getNext()
}
}

也不要在每个请求时都调用Database.Database().reference()。而是将其存储为变量。检查此以获取更多信息:Firebase best practices

关于 swift 火力地堡 : loop through data and only start the new loop if the old one has finished loading,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49096811/

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