【发布时间】:2020-12-15 04:29:13
【问题描述】:
我是 swift 的新手,我的问题对你们大多数人来说可能是愚蠢的。但无论如何,我都在尝试边做边学。这是我的问题。 我有一个模型:
import Foundation
import Firebase
struct special {
let name: String
let position: Int
let imageURL: String?
}
class SpecialList {
var specialList: [special] = []
init() {
}
func loadSpecial () {
db.collection("special").getDocuments { (querySnapshot, error) in
if let e = error {
print("Error\(e)")
} else {
if let snapshotDocuments = querySnapshot?.documents {
for doc in snapshotDocuments {
let data = doc.data()
if let name = data["name"] as? String, let position = data["position"] as? Int, let imageURL = data["imageURL"] as? String {
let newList = special(name: name, position: position, imageURL: imageURL)
self.specialList.append(newList)
}
}
}
}
}
}
}
我正在尝试在 ViewController 中实现它:
var specialList = SpecialList()
override func viewDidLoad() {
specialList.loadSpecial()
print(specialList.specialList)
}
实际上我需要的是从 firebase 检索的数据。我试图将它保存在var specialList: [special] = []但它总是空的。我认为我应该在 init() 中做一些事情,但没有找到正确的方法。
附:从firebase加载工作正常。已打印数据进行检查。
数据应该在collectionView中
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return specialList.specialList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SpecialCell", for: indexPath as IndexPath) as! SpecialCollectionViewCell
if let imageURL = specialList.specialList[indexPath.row].imageURL {
let url = URL(string: imageURL)
cell.specialPic.kf.setImage(with: url) // download foto
}
cell.specialName.text = specialList.specialList[indexPath.row].name
return cell
}
【问题讨论】:
-
在 self.specialList.append(newList) 上设置断点并检查是否调用
-
在这个函数里面它的 append specialList 并且工作正常。但是通过在 ViewController 中实现它是空的。
-
它是异步工作的,因此您必须在加载数据后对其进行处理。
-
那么,问题不在于我的班级SpecialList?我应该玩 DispatchQueue.main.async
标签: swift class methods properties initialization