2013-12-16 59 views
0

我遇到了問題,我正在使用GKLeaderboard並使用它來填充模型。我在獲取數據時沒有問題,當我去填充tableView和數據時發生問題,並且在調用填充TableView之前未填充數組。從我讀過的內容中我需要使用Grand Central Dispatch,以便它不會在主線程中加載。 任何幫助將不勝感激。使用Grand Central與GKLeaderboard調度

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

回答

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]; 

    }); 
}); 

希望這會有所幫助。

+0

我明白了,謝謝! –

相關問題