gpt4 book ai didi

swift - Firebase 删除不再属于查询的子项

转载 作者:行者123 更新时间:2023-11-30 12:16:17 27 4
gpt4 key购买 nike

我曾经使用 .value 调用 observe ,这会加载查询中的所有子项。实时地,当子项不再是查询的一部分(即它的时间戳太旧)时,.value 事件将被触发,并且子项的数据将从我的应用程序中删除。出于性能目的,我没有使用 .value 调用 observe,而是单独观察 .childAdded.childChanged.childRemoved 事件。但是,当子项不再是查询的一部分时,这些事件都不会被触发,并且子项的数据仍保留在我的应用程序中。我尝试观察 .childMoved 但也没有被解雇。如何复制观察 .value 的这一方面?这是一些代表我的代码:

class ViewController: UIViewController {

var children_query: DatabaseQuery!
var current_time: TimeInterval {
return Date().timeIntervalSince1970
}

override func viewDidLoad() {
super.viewDidLoad()

self.children_query = Database.database().reference().child("children").queryOrdered(byChild: "timestamp").queryStarting(atValue: current_time)
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

// refresh query every time this view appears (this is the root view controller so it comes and goes)
self.children_query = Database.database().reference().child("children").queryOrdered(byChild: "timestamp").queryStarting(atValue: current_time)

self.children_query.observe(.childAdded, with: { snapshot in
print(snapshot.value)
})

self.children_query.observe(.childChanged, with: { snapshot in
print(snapshot.value)
})

self.children_query.observe(.childRemoved, with: { snapshot in
print(snapshot.value)
})

self.children_query.observe(.childMoved, with: { snapshot in
print(snapshot.value)
})
}

override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.children_query.removeAllObservers()
}
}

最佳答案

在这种情况下,我为您提供简单的解决方案。只需将直接父级添加到所有值即可。

rootNode: [
{ your first value }
{ your second value }
....
/* you can add value here */
{your last value }
]

现在,您不再观察每个值,而是观察它们的直接父值。这样,从 dataSnapshot 的定义来看,无论内部发生什么变化,它都会触发 onMessageReceived() 函数。

关于swift - Firebase 删除不再属于查询的子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45402914/

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