我正在尝试将对象添加到数组中,以便使用UICollection View查看它们。我使用Firebase使用此代码:
// Retrieve the products and listen for changes
databaseHandle = ref?.child("Products").observe(.childAdded, with:
{ (snapshot) in
// Code to execute when new product is added
let prodValue = snapshot.value as? NSDictionary
let prodName = prodValue?["Name"] as? String ?? ""
let prodPrice = prodValue?["Price"] as? Double ?? -1
let prodDesc = prodValue?["Description"] as? String ?? ""
var prodToAddToView = Product(name: prodName, price: prodPrice, currency: "USD", description: prodDesc, location: "USA")
self.products.append(prodToAddToView)
})
但是当循环完成时,不会显示任何对象。另一方面,使用此代码:
var pr = Product(name: "a", price: 3, currency: "3", description: "SDF", location: "ASD")
products.append(pr)
该对象显示在UICollectionView中。如果我以与第二种方法相同的方式添加更多产品,也会显示它们。我错过了什么?在范围内添加一个对象不会影响数组吗?
另外 - 在调试的时候,我在observe函数中看到prodToAddToView被创建了。
产品属于[产品]
编辑:
此代码位于我的" ViewDidLoad"函数,因为我想在视图加载之前加载所有产品。
答案 0 :(得分:1)
您需要在self.collectionView.reloadData()
self.products.append(prodToAddToView)
DispatchQueue.main.async {
self.collectionView.reloadData()
}
完整代码
databaseHandle = ref?.child("Products").observe(.childAdded, with:
{ (snapshot) in
// Code to execute when new product is added
let prodValue = snapshot.value as? NSDictionary
let prodName = prodValue?["Name"] as? String ?? ""
let prodPrice = prodValue?["Price"] as? Double ?? -1
let prodDesc = prodValue?["Description"] as? String ?? ""
var prodToAddToView = Product(name: prodName, price: prodPrice, currency: "USD", description: prodDesc, location: "USA")
self.products.append(prodToAddToView)
DispatchQueue.main.async {
self.collectionView.reloadData()
}
})