Как ждать заполнения массива в Swift - PullRequest
0 голосов
/ 10 апреля 2020

Я пишу приложение на Swift и у меня возникают проблемы с заполнением таблицы правильно. Я получаю свои данные из Firestore и у меня есть класс, чтобы помочь мне получить эти данные. Основой c процесса является то, что у меня есть функция getProducts, которая устанавливает переменную локального массива с продуктами. Следующим шагом является создание массива объектов в моем классе просмотра таблиц, но, по-видимому, существует ошибка, из-за которой мой просмотр таблицы собирается до того, как моя функция успеет загрузить массив. Так что мой loadProducts заполняет массив продуктов, но мой счет, кажется, равен 0.

Надеюсь, вы, ребята, можете помочь, заранее спасибо

Мой код:

class ProductTableViewController: UITableViewController {

    var products = [Product]()
    override func viewDidLoad() {
        super.viewDidLoad()
            loadProducts()
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return products.count
    }

    private func loadProducts(){
        let dbhelper = DBHelper()
        dbhelper.getProducts(){ success in
            self.products = dbhelper.products
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "ProductTableViewCell"
        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? ProductTableViewCell  else {
            fatalError("The dequeued cell is not an instance of ProductTableViewCell.")
        }

        let product = products[indexPath.row]
        cell.titleLabel.text = product.Titel
        cell.priceLabel.text = product.Prijs


        return cell
    }
}

1 Ответ

0 голосов
/ 10 апреля 2020

Внутри вы загружаете продукты весело c добавьте статистику перезагрузки представления таблицы, чтобы перезагрузить таблицу с вашими новыми данными:

private func loadProducts(){
    let dbhelper = DBHelper()
    dbhelper.getProducts(){ success in
        self.products = dbhelper.products
        Self.tableView.reloadData()
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...