等待一个区块完成

我有一个UITableView,我试图获得行数。 但是,我在使用块时遇到了麻烦。 在下面的代码中,我只想返回count,但是我现在理解块是异步的。 我环顾四周试图找到一个解决方案,但没有一个工作。 我尝试过的一个解决方案是: 如何等待异步调度块完成? 但是当我点击按钮进入带有桌子的视图时,它只是在点击按钮时冻结。 我尝试了其他一些,但他们也没有工作。

- (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; } 

有人可以帮我正确地count回来吗?

你应该使用回调块。 不要试图使异步代码同步运行。

此外,您无需将GlobalVars单例保留在匹配数组中。 它可以被认为是糟糕的设计。

 typedef void(^CallbackBlock)(id value); - (void)viewDidLoad { [super viewDidLoad]; //show some sort of loading "spinner" here [self loadMatchesWithCallback:(NSArray *matches) { //dismiss the loading "spinner" here self.matches = matches; [self.tableView reloadData]; }]; } - (void)loadMatchesWithCallback:(CallbackBlock)callback { GlobalVars *globals = [GlobalVars sharedInstance]; GKLocalPlayer *localPlayer = [[GameCenterHelper sharedInstance] getLocalPlayer]; [[GameCenterHelper sharedInstance] getMatches:^(NSArray *matches) { NSLog(@"Matches: %@", matches); NSMutableArray *filteredMatches = [NSMutableArray array]; for (GKTurnBasedMatch *match in matches) { for (GKTurnBasedParticipant *participant in match.participants) { if ([participant.playerID isEqualToString:localPlayer.playerID]) { if (participant.status == GKTurnBasedParticipantStatusInvited) { [filteredMatches addObject:match]; break; //you don't want to add multiples of the same match do you? } } } } if (callback) callback(filteredMatches); }]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.matches.count; }