Как я могу запустить функцию до моего кода расширения в Swift? - PullRequest
0 голосов
/ 23 марта 2019

Я работаю над проектом и использую tableView для загрузки данных. Проблема в том, что мне нужно, чтобы количество ячеек определялось конкретной функцией. Мой tableView устанавливает количество ячеек в добавлении, которое я добавил, поэтому независимо от того, где я вызываю функцию, оно все равно выполняется вторым. Любая помощь будет очень признателен, вот мой код (функция и расширение):

func setNumCells() {
    let uid = Auth.auth().currentUser?.uid
    var ref: DatabaseReference!
    ref = Database.database().reference()

    let applicationReference = ref.child("applications")

    ref.child("applications").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
        if let dictionary = snapshot.value as? [String: AnyObject] {
            print("So far")
            let array = Array(dictionary.keys)
            print(array)
            for i in 0..<array.count {
                ref.child("applications").child(uid!).child(String(array[i])).observeSingleEvent(of: .value, with: { (snapshot) in
                    if let dictionary = snapshot.value as? [String: AnyObject] {
                        let array = Array(dictionary.keys)
                        self.numApplications += array.count - 1
                    }
                })
            }
        }
    })
}

... 

extension ApplicationViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return numApplications
    }

    func tableView(_ tableView: UITableView, cellForRowAt inde xPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.backgroundColor = UIColor.red
        tableView.rowHeight = 85
        cell.textLabel?.text = "\(indexPath.row)"

        return cell
    }
}

1 Ответ

1 голос
/ 23 марта 2019

Вы должны вызвать reloadData в табличном представлении и в главном потоке после получения всех данных

Рекомендуемый API для обработки времени: DispatchGroup

func setNumCells() {
    let uid = Auth.auth().currentUser?.uid
    var ref: DatabaseReference!
    ref = Database.database().reference()

    let applicationReference = ref.child("applications")
    let group = DispatchGroup()

    ref.child("applications").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
        if let dictionary = snapshot.value as? [String: AnyObject] {
            print("So far")
            let array = Array(dictionary.keys)
            print(array)
            for item in array {
                group.enter()
                ref.child("applications").child(uid!).child(String(item)).observeSingleEvent(of: .value, with: { (snapshot) in
                    if let dictionary = snapshot.value as? [String: AnyObject] {
                        let array = Array(dictionary.keys)
                        self.numApplications += array.count - 1
                    }
                    group.leave()
                })
            }
            group.notify(queue: DispatchQueue.main) {
               self.tableView.reloadData()
            }
        }
    })
}

Примечания:

  • for i in 0..<array.count ужасно, так как индекс на самом деле не нужен. Смотрите мой улучшенный код.
  • Никогда не создавать ячейки табличного представления с инициализатором по умолчанию. Повторное использование их.

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...