I am creating a turn based game using Game Center and GKTurnBasedMatch
.
To display the list of games in a table view in my root controller, I'm calling the following method:
-(void)reloadTableView
{
self.matchesTable.hidden = YES;
[_activityIndicator startAnimating];
[GKTurnBasedMatch loadMatchesWithCompletionHandler: ^(NSArray *matches, NSError *error)
{
if (error)
{
NSLog(@"loadMatchesWithCompletionHandler error:- %@", error.localizedDescription);
} else
{
for (GKTurnBasedMatch *m in matches)
{
// Download match data for each match
[m loadMatchDataWithCompletionHandler:^(NSData *matchData, NSError *error)
{
if (error)
{
NSLog(@"loadMatchDataWithCompletionHandler:- %@", error);
} else
{
[self processMatches]; // extracts match data to use in UI
}
}];
// Snipped - Code here to add each match to the relevant array ('My turn', 'Their turn' or 'Game over') for display in the table
}
[self.matchesTable reloadData];
self.matchesTable.hidden = NO;
[_activityIndicator stopAnimating];
}
}];
}
I want the order of tasks to be:
1) Hide matchesTable
and start the activity indicator
2) Call loadMatchesWithCompletionHandler
3) For each match, call loadMatchDataWithCompletionHandler
4) Call [self processMatches]
on each match
5) Put each match into the relevant array
6) Stop the activity indicator and show matchesTable
However, the code runs all the way through so fast that point 6 is executed before any match data has had time to download, meaning old data is displayed in my table.
So my big question is: how do I make the program wait until every match has downloaded its match data before continuing with the rest of the method? (ie pause after point 4, and only start point 5 once match data for every match has finished downloading)