This question already has an answer here:
- Return value for function inside a block 3 answers
I have a UITableView and I'm attempting to get the number of rows. However, I'm having trouble using blocks. In the code below I'd just like to return count, but as I now understand blocks are asynchronous. I've looked around trying to find a solution but none of them worked. One solution I tried was this: How do I wait for an asynchronously dispatched block to finish? but when I clicked on the button to go to the view with the table, it just froze when the button was clicked. I tried some others, but they also did not work.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
GlobalVars *globals = [GlobalVars sharedInstance];
__block int count = 0;
GKLocalPlayer *localPlayer = [[GameCenterHelper sharedInstance] getLocalPlayer];
[[GameCenterHelper sharedInstance] getMatches:^(NSArray *matches) {
NSLog(@"Matches: %@", matches);
for (GKTurnBasedMatch *match in matches) {
for (GKTurnBasedParticipant *participant in match.participants) {
if ([participant.playerID isEqualToString:localPlayer.playerID]) {
if (participant.status == GKTurnBasedParticipantStatusInvited) {
[globals.matchesReceived addObject:match];
count++;
NSLog(@"INVITED");
}
}
}
}
}];
return count;
}
Could someone help me properly get count
returned?
You should be using callback blocks. Don't try to make asynchronous code behave synchronously.
Also, there's no need to have your GlobalVars singleton hold onto the array of matches. It could be considered bad design.