在Firebase中更改值后移除观察者 [英] Remove observer after value change in Firebase

查看:94
本文介绍了在Firebase中更改值后移除观察者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ViewController中有全局的观察者,并且需要一些不同的观察者来获取特定的值,比如下面的值。是否有可能在值更改后删除观察者一次?

  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 call ref.removeObserverWithHandle(handle) inside the block.

这篇关于在Firebase中更改值后移除观察者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆