使用Grand Central Dispatch和GKLeaderboard

时间:2013-12-16 04:00:39

标签: ios grand-central-dispatch game-center

我遇到了一个问题,我目前正在使用GKLeaderboards并使用它来填充模型。我在获取数据时没有问题,当我用数据填充tableView时,我的问题出现了,并且在调用填充TableView之前没有填充数组。从我所读到的,我需要使用Grand Central Dispatch,以便它不会加载到主线程上。 任何帮助将不胜感激。

+(EILeaderBoardModel *)scoresAndNameFromLeaderBoard
{
static EILeaderBoardModel *leaderBoard = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    leaderBoard = [[EILeaderBoardModel alloc] init];
    leaderBoard.highScorePlayerArray  = [[self class] GameCenterLeaderBoard];
});
return leaderBoard;
}
+ (NSMutableArray *)GameCenterLeaderBoard
{
NSMutableArray *_highScorePlayer = [NSMutableArray new];

GKLeaderboard *leaderboardRequest = [[GKLeaderboard alloc] init];

leaderboardRequest.playerScope = GKLeaderboardPlayerScopeGlobal;
leaderboardRequest.timeScope = GKLeaderboardTimeScopeAllTime;
leaderboardRequest.range = NSMakeRange(1, 20);
leaderboardRequest.identifier = GameHighscoreIdentifier;

[leaderboardRequest loadScoresWithCompletionHandler: ^(NSArray *scores, NSError *error) {

    if (error != nil)
    {
        // Handle the error.
    }
    if (scores != nil)
    {

        for (NSUInteger i = 0; i < scores.count; i++) {
            GKScore *score = (GKScore *)scores[i];

            [GKPlayer loadPlayersForIdentifiers:@[score.playerID] withCompletionHandler:^(NSArray *players, NSError *error) {

                GKPlayer *player = (GKPlayer *)players[0];

                [player loadPhotoForSize:GKPhotoSizeSmall withCompletionHandler:^(UIImage *photo, NSError *error) {

                    if (error != nil) {

                    }

                    UIImage *_avatar;
                    if (photo != nil) {
                        _avatar = photo;
                    } else {
                        _avatar = [UIImage imageNamed:@"unknownPersonImage.png"];
                    }

                    EIPlayer *currentPlayer = [EIPlayer nameLabel:player.displayName
                                                       scoreLabel:[NSString stringWithFormat:@"%llD",score.value]
                                                           avatar:_avatar];

                    [_highScorePlayer addObject:currentPlayer];

                }];
            }];
        }
    }
}];
return _highScorePlayer;
}

1 个答案:

答案 0 :(得分:0)

dispatch_queue_t queue = dispatch_queue_create("com.yourQueue.company", 0);
dispatch_queue_t main = dispatch_get_main_queue();

dispatch_async(queue, ^{ 

 // Do all your data fetching work here
 // also like adding values to arrays.

    dispatch_async(main, ^{ 

       // Do all your UI update logic here like updating data into tables.

       [self.tableView reloadData];

   });
});

希望这会有所帮助。