在Firebase中增加数据点的最简单方法

在Firebase中增加数据点的最简单方法

本文介绍了在Firebase中增加数据点的最简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在Firebase中增加一条数据.

I'm having trouble incrementing a piece of data in Firebase.

Firebase {
    clickedCounter: 0
}

这是我的代码:

@IBAction func plus(sender: UIButton) {
        FIRDatabase.database().reference().child("clickedCounter").observeEventType(.Value) { (snap: FIRDataSnapshot) in
            let value = FIRDatabase.database().reference().child("clickedCounter") as? NSNumber
            let increment = ((value?.intValue)! + ((1 as? NSNumber)?.intValue)!) as? NSNumber
            FIRDatabase.database().reference().child("clickedCounter").setValue()
            self.clickLabel.text = snap.value?.description as String!
        }
    }

我也尝试过:

@IBAction func plus(sender: UIButton) {
        FIRDatabase.database().reference().child("clickedCounter").observeEventType(.Value) { (snap: FIRDataSnapshot) in
            FIRDatabase.database().reference().child("clickedCounter").setValue((snap.value?.description)! + 1)
            self.clickedLabel.text = snap.value?.description as! String!
        }
    }

首先,我的警告是:

Cast from Int32 to NSNumber always fails

Conditional cast from NSNumber to NSNumber always succeeds

Cast from FIRDatabaseReference to NSNumber always fails

运行后,我在let increment....上收到错误:Thread 1: EXC_BAD_INSTRUCTION

After I ran it, I got the error on let increment.... : Thread 1: EXC_BAD_INSTRUCTION

第二次错误是:

Binary operator + cannot be applied to operands of the type String and Int

  1. 当我以为我在Firebase中将snap.value?.description定义为Int时,我对我的snap.value?.description是一个字符串感到困惑.

  1. I'm confused as to how my snap.value?.description is a String when I thought I defined it in Firebase as an Int.

为什么总是成功的我会收到警告?

Why do I get a warning when something always succeeds?

是否有更好的方法来做到这一点?

Is there a better way to do this?

谢谢!

推荐答案

为什么不这样做(v2.x Firebase代码,但您知道了)

Why not (v2.x Firebase code but you get the idea)

counterRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
     let valString = snapshot.value
     var value = valString.intValue
     value = value + 1
     counterRef.setValue("\(value)")
})

如果要由多个用户频繁更新,则也要利用一个事务块.

If this is going to be updated frequently by multiple users, leverage a transaction block as well.

这篇关于在Firebase中增加数据点的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 07:45