问题
In the Awesome that is Firebase, you do this
var r1: DatabaseReference? = nil
and then this
r1 = Database.database().reference(withPath: "score/bucks")
r1!.observe(.childAdded) { snapshot in ... }
and then have fun,
but eventually you must do something like this
private func clearObservations() { // call from viewDidDisappear
if r1 != nil {
r1?.removeAllObservers()
r1 = nil
}
if r2 != nil {
r2?.removeAllObservers()
r2 = nil
}
.. etc etc etc etc etc etc :/ :/
}
{ Critical aside: it's worth noting YOU CAN NOT do that in deinit, you MUST do it in viewDidDisappear }
It does seem pretty incredible that one cannot just
r1 = nil // and this will remove the observor
Is it honest to goodness the case that:
- if you just nil a
DatabaseReference, - i.e. you do NOT bother to
removeAllObservors, - in fact the observation will just keep going?
Is that right?
I just want to absolutely clarify this and get it down on the record - it will probably help future googlers (interestingly, I couldn't really google up a clear marginalia on this anywhere).
I realize you can put them in a hokey array, etc, but it seems incredible that nil'ing one does not stop the observation?!
Footnote
One thing that's always disturbed me. If you carefully read the doco for removeAllObservors, really all it asserts is that it drops or terminates the closure you added. It doesn't, really, say that removeAllObservors actually has the guts of Firebase in the iPhone, actually call home and stop doing the observation. I spend a lot of time worrying about that detail.
回答1:
As I explained in the comments, you must remove observers manually because Firebase hold references to your DatabaseReference and to your closures. If you nil the DatabaseReference it's not deallocating it, it has another reference to it.
I guess from the docs that this what's happening
Many times you'll see in the docs:
Use removeObserverWithHandle: to stop receiving updates.
So this is the way, and the only way.
来源:https://stackoverflow.com/questions/47320099/is-it-absolutely-correct-that-niling-a-firebase-databasereference-does-not-stop