我想在viewController中初始化一个 Store 对象,并使用在 Store 类中获取的数据设置视图的UI元素,该类本身从其他模型类选择和产品。
我的问题是:
在尝试在viewController中使用获取的数据之前,如何确保完成模型类中的获取?
我尝试过的事情:
在了解了如何处理异步调用之后,我的直觉是使用完成处理程序,但是当嵌套异步调用时,我无法弄清楚如何实现这一点。如果我取得了进展,将继续阅读完成处理程序并进行编辑。
如果完成处理程序是错误的方法,我将非常感谢被指出正确的方向。
class StoreViewController: UIViewController {
@IBOutlet weak var storeNameLabel: UILabel!
@IBOutlet weak var storeAddressLabel: UILabel!
@IBOutlet weak var storeSelection: UITableView!
var store = Store(storeID: "Store123") // Setting this via segue in actual app
override func viewDidLoad() {
super.viewDidLoad()
storeNameLabel.text = store.name
storeAddressLabel.text = store.address
}
// tableView functions. the tableView storeSelection displays all
// the products in the store's selection
{...}
}
Store 模型类:
class Store() {
var storeID = String()
var name: String?
var address: String?
var selection: Selection?
init(storeID: String){
self.storeID = storeID
fetchStoreInfo()
self.selection = Selection(storeID: storeID)
}
//Fetches name and address from Firebase. Async call.
func fetchStoreInfo(){
let ref = Database.database().reference()
ref.child("stores").child(storeID).observeSingleEvent(of: .value, with: { (snapshot) in
let storeSnapshot = snapshot.value as? NSDictionary
self.name = storeSnapshot?["name"] as? String ?? ""
self.address = storeSnapshot?["address"] as? String ?? ""
})
}
}
选择模型类。视图将具有带有部分的tableView。这些部分应以特定顺序显示。在实际的应用程序中将处理此逻辑。
class Selection() {
var storeID:
var selection: [String: [Product]] //Dict with price point as key
var selectionSection: [Int: String]
init(storeID: String){
self.storeID = storeID
fetchPricePoints()
}
func fetchPricePoints(){} // Fetches the store's different price
// points from Firebase. Async call
func fetchProducts() {
//fetch array of product IDs from Firebase. Async call
for productID in ProductIDs {
let product = Product(productID)
self.selection![product.pricePoint!].append(product)
}
}
}
最后是 Product 模型类。这是最后一个要初始化的模型类。
class Product {
//Contains product info variables whose data it fetches
// from Firebase. Async call.
}