从firebase中检索对象

时间:2016-06-24 08:05:55

标签: ios arrays swift

我正在研究简单程序 - 我创建了产品对象,然后计算他们的卡路里。

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

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

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

这是我的Products.I模型通过字典

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
        }


    }


}

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您只在viewDidLoad()

中启动了products的空数组
self.products = []

并且不会在任何地方分配任何东西。这就是为什么你得到空数组。

并在updateCalory()方法上循环空数组(包含零项的数组)

编辑1

你必须追加product

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

                }
            }