[英]Retrieving objects from firebase
I'm working on simple program - I create objects of products and then I count their calories. 我正在研究简单的程序-创建产品对象,然后计算它们的卡路里。
I want to count sum of all calories of my products. 我想计算产品中所有卡路里的总和。
I've created a method, allowing me to save data properly in Firebase, but I got stuck while retrieving them: 我创建了一个方法,可以将数据正确保存在Firebase中,但是在检索数据时遇到了麻烦:
import UIKit
import Firebase
class TotalViewController: UIViewController {
var products = [Products]()
@IBOutlet weak var calotyCounter: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
DataService.dataService.PRODUCT_BASE.observeEventType(.Value, withBlock: { snapshot in
print(snapshot.value)
self.products = []
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshots {
if let postDictionary = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let product = Products(key: key, dictionary: postDictionary)
}
}
}
self.updateCalory()
})
// Do any additional setup after loading the view.
}
func updateCalory() {
var CaloryArray: [Int] = []
for product in products {
CaloryArray.append(Int(product.productCalories))
}
print (CaloryArray)
calotyCounter.text? = String(CaloryArray.reduce(0, combine: +))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
I got an empty array, instead of array of objects callory value. 我得到了一个空数组,而不是对象表述值的数组。
Here is my model of Products.I made it through dictionary 这是我的产品模型。我通过词典制作的
import Foundation
import Firebase
class Products {
private var _productName: String!
private var _productCalories: Int!
var productName: String {
return _productName
}
var productCalories: Int {
return _productCalories
}
init(key: String, dictionary: Dictionary<String, AnyObject>) {
if let calories = dictionary["calories"] as? Int {
self._productCalories = calories
}
if let name = dictionary["name"] as? String {
self._productName = name
}
}
}
What I'm doing wrong? 我做错了什么?
You have only initiated the empty array of products
in viewDidLoad() 您仅在viewDidLoad()中启动了
products
的空数组
self.products = []
and not assigning any thing to it anywhere. 而不是在任何地方分配任何东西。 thats why you are getting the empty array.
那就是为什么你得到空数组。
and on updateCalory()
method you are looping on empty array (array with zero items) 在
updateCalory()
方法上,您正在空数组(零项数组updateCalory()
上循环
EDIT 1 编辑1
you must append the product
ie 您必须附加
product
即
let product = Products(key: key, dictionary: postDictionary)
to your products
array in loop. 循环到您的
products
数组。 like this 像这样
for snap in snapshots {
if let postDictionary = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let product = Products(key: key, dictionary: postDictionary)
self. products.append(product) // add this line
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.