Firebase请求方法后,对象= nil

时间:2019-05-10 14:43:58

标签: swift class object scope

我正在使用Firebase实时数据库。 我请求数据并将其放入使用For循环制作的对象中 但是如果我想在请求方法之后使用该对象,则为空。 这是代码,请参阅注释 有什么建议吗?

我尝试使用“类”,“结构”和“初始化”

var StockOb : [StockModel2] = []
var tempstock : [StockModel2] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        self.StockOb = [StockModel2]()
        self.tempstock = [StockModel2]()
}
func getdata() 
{
    let ref = Database.database().reference()

        ref.child("MyStock").observe(.value) { (snapchot) in

            let AllStock = snapchot.value as! NSDictionary



            for (key,_) in AllStock {

                let ab = StockModel2()
                let OneStock:NSObject = AllStock[key] as! NSObject
                ab.name = OneStock.value(forKey: "name") as? String
                ab.quan = OneStock.value(forKey: "quan") as? Int
                ab.price = OneStock.value(forKey: "price") as? Int
                ab.total = OneStock.value(forKey: "total") as? Int







                self.StockOb.append(ab)
            }
            /// here it's ok 
            print("[+] iside firebase method = \(self.StockOb[0].price!)")
            self.tempstock = self.StockOb
        }
        /// here it's nil
        print(self.tempstock[0].name) // nil
        print(self.StockOb[0].name) // nil
}

这是我的对象:

class StockModel2 : NSObject{
    var name :String!
    var quan : Int!
    var price : Int!
    var total : Int!


}

将对象添加到“ self.StockOb”或“ self.tempstock”后,我想在任何地方使用我的对象

1 个答案:

答案 0 :(得分:0)

这里

/// here it's nil
print(self.tempstock[0].name) // nil
print(self.StockOb[0].name) // nil

您在firebase回调之外访问变量,因此会崩溃

func getdata() {

    let ref = Database.database().reference() 
        ref.child("MyStock").observe(.value) { (snapchot) in

            let allStock = snapchot.value as! [String:[String:Any]]  
            Array(allStock.values).forEach { 
                let ab = StockModel2() 
                ab.name = $0["name"] as! String
                ab.quan = $0["quan"] as! Int
                ab.price = $0["price"] as! Int
                ab.total = $0["total"] as! Int 
                self.stockOb.append(ab)
            } 

            self.tempstock = self.stockOb 

        /// here it's not nil
        print(self.tempstock[0].name) // here
        print(self.stockOb[0].name) // here
    }
} 

您也不必在viewDidLoad内写这个

self.stockOb = [StockModel2]()
self.tempstock = [StockModel2]()

因为他们是在这里声明的

var stockOb : [StockModel2] = []
var tempstock : [StockModel2] = []