M
M
MarsFM2017-04-14 17:09:57
iOS
MarsFM, 2017-04-14 17:09:57

Why isn't the value overwritten in the closure?

Plz tell me why amountGame is nil?

class MyGameTVC: UITableViewController {

    var currentUser: FIRUser!
    var ref: FIRDatabaseReference!
    var amountGame: Int!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        currentUser = FIRAuth.auth()?.currentUser
        
        ref = FIRDatabase.database().reference().child("users/\(currentUser.uid)/idMyGame")
        
        ref.observeSingleEvent(of: .value, with: {  snapshot in
            if let dict = snapshot.value as? [String: AnyObject] {
                self.amountGame = dict.count
            }
        })
        
        print(amountGame) // ?
        
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
ManWithBear, 2017-04-14
@ManWithBear

Because Optional is initialized by default with a value of nil.
Why doesn't it change in clojure? Most likely it is asynchronous and is executed after your print

N
nanosem, 2017-04-19
@nanosem

First closure's pass a link to self
stackoverflow.com/questions/24320347/shall-we-alwa...

ref.observeSingleEvent(of: .value, with: { [weak self]  snapshot in
            if let dict = snapshot.value as? [String: AnyObject] {
                self?.amountGame = dict.count
            }
        })

Secondly, firbase and similar services work in background threads,
And your assignment lies in the main (main thread)
Solution: (or rather, one of them)
Use DispatchGroup
class MyGameTVC: UITableViewController {

    var currentUser: FIRUser!
    var ref: FIRDatabaseReference!
    var amountGame: Int!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        currentUser = FIRAuth.auth()?.currentUser
        
        ref = FIRDatabase.database().reference().child("users/\(currentUser.uid)/idMyGame")
        
        let group = DispatchGroup() 
        group.enter()

        ref.observeSingleEvent(of: .value, with: { [weak self] snapshot in
            if let dict = snapshot.value as? [String: AnyObject] {
                self?.amountGame = dict.count
            }

        group.leave()

        })
        group.notify(queue: DispatchQueue.main) {
              print(amountGame) // ?
        }
        
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question