【发布时间】:2023-04-09 11:24:01
【问题描述】:
在学习 Swift 时,我从来没有真正理解过的一件事是闭包。我总是觉得和他们一起工作很困惑。
谁能解释一下我在下面的代码中做错了什么。
for id in myCircles{
var circleName = ""
var circleCategory = ""
var circleID = ""
ref.child("\(id)").observeSingleEvent(of: .value, with: { snapshot in
let value = snapshot.value as? NSDictionary
circleName = value?["name"] as? String ?? ""
circleCategory = value?["category"] as? String ?? ""
circleID = value?["id"] as? String ?? ""
self.defaults.setValue([circleName, circleID, circleCategory], forKey: "newestCircle"+"\(id)")
}) { error in
}
//the problem is that the part below gets executed before the closure, which is when the value should be added. The part below must be executed after the closure.
let retrievedData = self.defaults.value(forKey: "newestCircle"+"\(id)") as? [String] ?? ["","",""]
self.addCircle(circleName: retrievedData[0], circleID: retrievedData[1], circleCategory: retrievedData[2])
}
正如评论所说,我的 .observingSingeEvent 闭包是在闭包下方的代码之后调用的。它不仅在闭包下面的代码之后被调用,而且在整个 for 循环之后被调用,如果它在循环内部被调用的话,它会被调用多次。我不明白这是为什么,有人可以帮助我吗?
【问题讨论】:
-
看看我对this question的简短回答
标签: ios swift firebase firebase-realtime-database closures