This question already has answers here:
Return value for function inside a block
                                
                                    (3个答案)
                                
                        
                                5年前关闭。
            
                    
我有一个UITableView,我试图获取行数。但是,我在使用块时遇到麻烦。在下面的代码中,我只想返回count,但是据我所知,块是异步的。我四处寻找解决方案,但是没有一个起作用。我尝试的一种解决方案是:How do I wait for an asynchronously dispatched block to finish?,但是当我单击按钮以转到带有表的视图时,单击按钮时它只是冻结了。我尝试了一些其他方法,但它们也没有起作用。

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

10-08 05:52
查看更多