I am attempting to return an integer from a block I am calling. You can see it below:
-(NSInteger)globalRecord
{
__block NSInteger globalRecord = 0;
[GKLeaderboard loadLeaderboardsWithCompletionHandler:^(NSArray *leaderboards, NSError *error) {
GKLeaderboard *globalTaps = nil;
for (GKLeaderboard *lb in leaderboards) if ([lb.category isEqualToString:kGlobalLeaderboard]) globalTaps = lb;
[globalTaps loadScoresWithCompletionHandler:^(NSArray *scores, NSError *error) {
if ([scores count] != 0)
{
GKScore *topScore = [scores objectAtIndex:0];
globalRecord = topScore.value;
//42 here
}
}];
}];
//0 here
return globalRecord;
}
So I am trying to get the highest score from my leader-board in game center. I want my method to return the score once it's been received; however, it's not returning my score.
In the block it recognises the score, 42 in this case, however once we reach outside of the block and want to return the value, it's 0.
You are getting zero because the return is actually called BEFORE the block's execution. To get the globalRecord
value you should use a callback once the block loadScoresWithCompletionHandler
ends:
-(void)globalRecord
{
__block NSInteger globalRecord = 0;
[GKLeaderboard loadLeaderboardsWithCompletionHandler:^(NSArray *leaderboards, NSError *error) {
GKLeaderboard *globalTaps = nil;
for (GKLeaderboard *lb in leaderboards) if ([lb.category isEqualToString:kGlobalLeaderboard]) globalTaps = lb;
[globalTaps loadScoresWithCompletionHandler:^(NSArray *scores, NSError *error) {
if ([scores count] != 0)
{
GKScore *topScore = [scores objectAtIndex:0];
globalRecord = topScore.value;
[self globalRecordRetrieved:globalRecord];
//42 here
}
}];
}];
}
- (void)globalRecordRetrieved:(NSInteger)record{
NSLog(@"%d",record); //42 here
}