我在代码中删除Firebase观察者时遇到问题.这是结构的细分:
var ref = Firebase(url:"https://MY-APP.firebaseio.com/") var handle = UInt? override func viewDidLoad() { handle = ref.observeEventType(.ChildChanged,withBlock: { snapshot in //Do something with the data } } override func viewWillDisappear(animated: Bool) { if handle != nil { println("Removed the handle") ref.removeObserverWithHandle(handle!) } }
现在,当我离开viewcontroller时,我看到“Removed the handle”被打印出来,但是当我返回viewcontroller时,我的观察者会为每个事件调用两次.当我离开并再次返回时,它被召唤三次.等等.为什么观察者没有被移除?
解决方法
以为我有这个错误,但实际上我试图删除观察者的错误参考.
原始代码:
let ref: FIRDatabaseReference = FIRDatabase.database().reference() var childAddedHandles: [String:FIRDatabaseHandle] = [:] func observeFeedbackForUser(userId: String) { if childAddedHandles[userId] == nil { // Check if observer already exists // NOTE: - Error is caused because I add .child(userId) to my reference and // do not when I call to remove the observer. childAddedHandles[userId] = ref.child(userId).observeEventType(.ChildAdded) { [weak self] (snapshot: FIRDataSnapshot) in if let post = snapshot.value as? [String:AnyObject],let likes = post["likes"] as? Int where likes > 0 { self?.receivedFeedback(snapshot.key,forUserId: userId) } } } } func stopObservingUser(userId: String) { // THIS DOES NOT WORK guard let cah = childAddedHandles.removeValueForKey(userId) else { print("Not observing user") return } // Error! I did not add .child(userId) to my reference ref.removeObserverWithHandle(cah) }
固定代码:
func stopObservingUser(userId: String) { // THIS WORKS guard let cah = childAddedHandles.removeValueForKey(userId) else { print("Not observing user") return } // Add .child(userId) here ref.child(userId).removeObserverWithHandle(cah) }