在Firebase中更改值后移除观察者 [英] Remove observer after value change in Firebase
问题描述
var ref = Firebase(url:https://< FIREBASE -APP> .firebaseio.com /)
let handle = ref.observeEventType(.Value,withBlock:{snapshot in
//此处VALUE更改为NEW_VALUE
if snapshot.value as!String == NEW_VALUE {
//是否可以在这里删除句柄????
...这里的某些
}
$)
//不存在
... ref.removeObserverWithHandle(句柄)
这是您需要在Swift中采取额外步骤的情况之一,因为它没有意识到您可以安全地访问
解决这个问题的方法之一是:
$ handle
b $ b
let ref = Firebase(url:https://yours.firebaseio.com/)
var句柄:UInt = 0
句柄= ref.observeEventType(.Value,withBlock:{snapshot in
print (快照)
if snapshot.exists()&& snapshot.value as! String ==42{
print(Value is now 42)
ref.removeObserverWithHandle(handle)
}
})
通过显式初始化
句柄但是鉴于在调用块之前已经设置了句柄,我们可以在块内安全地调用
ref.removeObserverWithHandle(handle)
。I have global observer in ViewController and need some different observers inside it for specific values like one below. Is it possible to remove observer after value change once?
var ref = Firebase(url: "https://<FIREBASE-APP>.firebaseio.com/") let handle = ref.observeEventType(.Value, withBlock: { snapshot in //Here VALUE Changes to NEW_VALUE if snapshot.value as! String == NEW_VALUE { //IS IT POSSIBLE TO REMOVE HANDLE HERE???? ...something here } }) //NOT HERE ...ref.removeObserverWithHandle(handle)
解决方案This is one of the cases where you need to take an extra step in Swift, since it doesn't realize that you can safely access
handle
inside the block.One way of working around this is:
let ref = Firebase(url: "https://yours.firebaseio.com/") var handle: UInt = 0 handle = ref.observeEventType(.Value, withBlock: { snapshot in print(snapshot) if snapshot.exists() && snapshot.value as! String == "42" { print("The value is now 42") ref.removeObserverWithHandle(handle) } })
By explicitly initializing the
handle
variable, we remove the error from the Swift compiler. But given that the handle will have been set before our block is invoked, we can safely callref.removeObserverWithHandle(handle)
inside the block.这篇关于在Firebase中更改值后移除观察者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!