1
在我的應用我取實時數據是這樣的:火力地堡數據庫分離監聽
//Firebase
var ref: FIRDatabaseReference?
var handle: FIRDatabaseHandle?
override func viewDidLoad() {
ref = FIRDatabase.database().reference()
handle = ref?.child("posts").child(String(itemId)).observe(.childChanged, with: { (snapShot) in
if let item = snapShot.value as? String {
print(item)
}
})
.....
現在讀火力文檔我看到這一點:
觀察家當你離開一個不自動停止同步數據視圖控制器。如果觀察員沒有正確移除,它會繼續將數據同步到本地內存。
所以我添加了這個功能,當我退出VC是被炒魷魚:
@IBAction func backButtonDidTouch(_ sender: AnyObject) {
if let handle = handle {
ref?.removeObserver(withHandle: handle)
}
showNavBar = true
_ = navigationController?.popViewController(animated: true)
}
但我也可以調用removeObserver()
removeAllObservers()
insetad和文檔也說:
調用removeObserverWithHandle
或removeAllObservers
在偵聽器上不會自動刪除在其子節點上註冊的偵聽器;您還必須跟蹤這些引用或句柄以將其刪除。
所以在看我的代碼,我在做對嗎?我不想讓我的應用程序和火力之間的數據同步,當我離開我的VC
我應該使用removeAllObservers嗎? – Kiow
不是。你應該簡單地在你附加偵聽器的位置調用它:'ref?.child(「posts」)。child(String(itemId))。 removeObserverWithHandle ...' –
或者如果您只在使用observeSingleEvent時才獲取數據。那麼你不需要再取消它了。 –