gpt4 book ai didi

swift - Firebase 请求方法后 Object = nil

转载 作者:行者123 更新时间:2023-11-30 10:44:20 24 4
gpt4 key购买 nike

我正在使用 firebase 实时数据库。我请求数据并将其放入使用 For 循环创建的对象中但如果我想在请求方法之后使用该对象,它就是nul。这是代码并查看评论有什么建议吗?

我尝试使用“class”、“struct”和“init”

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”后,我想在任何地方使用它

最佳答案

这里

/// 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] = []

关于swift - Firebase 请求方法后 Object = nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56079926/

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