Reputation: 521
I have an app that contains a table view. The table view is populated by data pulled from Parse. To get the number of rows that I want the TableView to be populated with, I query parse.
var activeGamesCurrentUser = 0
gamesQuery.countObjectsInBackgroundWithBlock({
(count, error) -> Void in
let countedInt = Int(UInt32(count))
self.activeGamesCurrentUser = countedInt
})
But, when I attempt to return activeGamesCurrentUser for the number of rows, it is always 0 because the variable doesn't update outside of the completion block. If I print "countedInt" inside of the block, it is a number greater than 0.
I do not want to solve the problem like this:
var count = gamesQuery.countObjects()
activeGamesCurrentUser = count
The reason for this is because "countObjects()" is synchronous and will continue running in the foreground forever. Any help regarding this issue will be appreciated.
Edit:
Here is the full method:
var activeGamesCurrentUser = 0
func getRowNumber() {
if PFUser.currentUser() != nil && finished == true {
currentUserObjectId = PFUser.currentUser()?.objectId
let currentUser = PFUser.currentUser()
let challengedQuery = PFQuery(className: "Games")
challengedQuery.whereKey("challenged", equalTo: currentUserObjectId)
let challengerQuery = PFQuery(className: "Games")
challengerQuery.whereKey("challenger", equalTo: (currentUser?.objectId)!)
let gamesQuery = PFQuery.orQueryWithSubqueries([challengedQuery, challengerQuery])
gamesQuery.countObjectsInBackgroundWithBlock({
(count, error) -> Void in
let countedInt = Int(UInt32(count))
self.activeGamesCurrentUser = countedInt
})
}
override func viewDidLoad() {
super.viewDidLoad()
getRowNumber()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return activeGamesCurrentUser
}
Upvotes: 2
Views: 533
Reputation: 38162
Couple of things -
First, always access class properties inside the block with a weak reference to self.
Second, reload table once you are done updating your model.
weak var aBlockSelf = self
gamesQuery.countObjectsInBackgroundWithBlock({
(count, error) -> Void in
let countedInt = Int(UInt32(count))
aBlockSelf.activeGamesCurrentUser = countedInt
aBlockSelf.tableView.reloadData()
})
Upvotes: 3