gpt4 book ai didi

ios - 从 firebase 检索对象

转载 作者:行者123 更新时间:2023-11-30 13:18:27 24 4
gpt4 key购买 nike

我正在开发简单的程序 - 我创建产品对象,然后计算它们的卡路里。

我想计算我的产品所有卡路里的总和。​​

我创建了一个方法,允许我在 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.
}

我得到一个空数组,而不是对象调用值数组。

这是我的产品模型。我通过字典制作的

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
}


}


}

我做错了什么?

最佳答案

您仅在 viewDidLoad() 中启动了 products 的空数组

self.products = []

并且没有在任何地方给它分配任何东西。这就是为什么你得到空数组的原因。

并且在 updateCalory() 方法上,您在空数组(具有零个项目的数组)上循环

编辑 1

您必须附加产品,即

let product = Products(key: key, dictionary: postDictionary)

到循环中的products数组。像这样

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

}
}

关于ios - 从 firebase 检索对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38008552/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com