等待一个块完成

时间:2014-07-21 16:51:34

标签: ios objective-c objective-c-blocks

我有一个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吗?

1 个答案:

答案 0 :(得分:1)

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

此外,您无需将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;
}