Reputation: 71
Problem: I’m trying to access the value which is returned from completionHandler, to assign it to a variable which is outside the scope of completionHandler returned method. I can access the variable in the scope of the method, but I can’t from outside. I’ve tried to assign it to the class variable when I access, but didn’t work. Any ideas?
var marketler = [MarketModel]()
var marketAdiArray = [String]()
override func viewDidLoad() {
getMarkets { (marketdizi) in
self.objAryToTableView(markets: marketdizi)
print(self.marketAdiArray) // -> this returns the right array
}
print(self.marketAdiArray) // -> this returns an empty array
}
func getMarkets(completionHandler : @escaping ([MarketModel])->()) {
let uid = "userID(02)"
print("uid : \(uid)")
MobileUserViewModel().getUser(userId: uid, completionHandler: { (user) in
// here returns an user object
self.loginUser = user
MarketViewModel().getMarketFromDb(mobilUser: user, completionHandler: { (marketler) in
print("marketler : \(marketler)")
completionHandler(marketler)
})
})
}
func objAryToTableView(markets : [MarketModel]) {
var ary = [String]()
for m in markets {
ary.append(m.marketName as String!)
}
self.marketAdiArray = ary
}
Upvotes: 1
Views: 801
Reputation: 2897
The code inside the block (completion handler) is getting executed after getMarketFromDb
call succeeds. The code which is outside the block is executed just after the previous line where you don't have any data on the array.
If You need to trigger the UI update which updated data from data Db then you need to invoke the UI update from inside the completion block.
getMarkets { (marketdizi) in
self.objAryToTableView(markets: marketdizi)
print(self.marketAdiArray) // -> this returns the right array
self.tableView.reloadData()
}
print(self.marketAdiArray) // -> this returns an empty array
Upvotes: 2