Answer the question
In order to leave comments, you need to log in
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
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
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
}
})
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 questionAsk a Question
731 491 924 answers to any question