将FIRDataSnapshot转换为自定义类型 [英] convert FIRDataSnapshot to custom type
问题描述
我试图将一个FIRDataSnapshot转换为自定义类型(即我知道每个孩子
将有一个名称,数字和电子邮件)
I am trying to convert a FIRDataSnapshot to a custom type (i.e. I know that each child will have a Name, Number, and Email )
当我运行下面的代码,每个孩子包含一个名称,数字和电子邮件的JSON树打印到控制台。
When I run the code below, a JSON tree with the each child containing a Name, Number, and Email prints to the console.
因此,我想将快照存储为具有每个属性的自定义类型PersonInfo。这样我可以在我的应用程序中改变这些数据。我需要使用PersonInfo变量我将这些数据存储在我的应用程序的各个部分。
So I want to store the snapshot as a custom type "PersonInfo" that has each of those properties. That way I can alter this data within my app. I need to use the "PersonInfo" variable I store this data into in various parts of my app.
ref.observeSingleEventOfType(.Value, withBlock: { (snapshot: FIRDataSnapshot) in
print(snapshot)
})
推荐答案
您可以定义一个自定义类PersonInfo作为模型。
You can define a custom class PersonInfo that will act as a model.
class PersonInfo: NSObject {
var pName: String
var pNumber :String
var pEmail: String
let ref: FIRDatabaseReference?
init( name: String, number: String, email: String) {
self.pName = name
self.pNumber = number
self.pEmail = email
self.ref = nil
}
init(snapshot: FIRDataSnapshot) {
pName = snapshot.value!["pName"] as! String
pNumber = snapshot.value!["pNumber"] as! String
pEmail = snapshot.value!["pEmail"] as! String
ref = snapshot.ref
}
convenience override init() {
self.init(name:"",number: "", email: "")
}
}
observeSingleEventOfType 当您有快照
时,您可以遍历其子代并获取每个Person:
And inside your observeSingleEventOfType
when you have snapshot
, you can iterate over its children and fetch each Person as:
for item in snapshot.children{
var person = PersonInfo(snapshot:item);
yourList.append(person);
}
因此,您将有一个 PersonInfo
模型对象,您可以稍后访问。
So, you will have a list of PersonInfo
model objects that you can access later.
这篇关于将FIRDataSnapshot转换为自定义类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!