Swift - значение не обновляется после обработчика завершения - PullRequest
0 голосов
/ 15 сентября 2018

Я новичок в программировании Swift и пытаюсь вернуть значение для моего tableView numberOfSections.Я также новичок в обработчиках завершения.Если я перехожу в режим отладки и запускаю свой код построчно, счетчик «обновляется» в numberOfSections.Однако, когда дело доходит до оператора return, count остается со значением 0.

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

    var count = 0
    let firebase = ref.child("Menu").child("Category").child("Cookies")
    getCount(ref: firebase) { (myCount) in
        print("Complete")
        count = myCount
    }
    return count
}

func getCount(ref:DatabaseReference, completion: @escaping (Int) -> ()){
    var count = 0
    ref.observeSingleEvent(of: .value) { (snapshot) in
        count = Int(snapshot.childrenCount)
        completion(count)
    }
}

Ответы [ 2 ]

0 голосов
/ 15 сентября 2018

Существует несколько причин, по которым переменная count не обновляется в функции numberOfSections.

  1. Count - это Int, что делает его типом значения, что означает, что в замыкании делается копияпоэтому счетчик внутри замыкания отличается от счетчика вне замыкания.
  2. Выборка из базы данных является асинхронной, что означает, что счетчик будет возвращен и выйдет из области видимости до выполнения замыкания.

Попробуйте, чтобы увидеть, работает ли он.

    // this variable now lives beyond the scope of the function
    var sectionCount: Int = 0 

    // fetch every time you come into this screen, 
    // so pushing and popping new screens on top of this one
    // will update it
    override func viewWillAppear() {
        super.viewWillAppear()

        // make your async call to your db
        let firebase = ref.child("Menu").child("Category").child("Cookies")

        // remember to weak reference 'self' to avoid retain cycles
        getCount(ref: firebase) { [weak self] (myCount) in
            // update the section count
            self?.sectionCount = myCount
            // tell the table view to update itself, this will tell it 
            // to call numberOfSections, cellForIndex, and other functions 
            // to update the table view 
            self?.tableView.reloadData()
        }
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return self.sectionCount
    }
0 голосов
/ 15 сентября 2018

Процесс асинхронный, вам нужно

var count = 0 // instance var

override func viewDidLoad() {
    super.viewDidLoad() // you missed this =D
    let firebase = ref.child("Menu").child("Category").child("Cookies")
    getCount(ref: firebase) { (myCount) in
        print("Complete")
        count = myCount
        self.tableView.reloadData()
    }
}

override func numberOfSections(in tableView: UITableView) -> Int {
    return count
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...