0

我试图从我正在调用的块中返回一个整数。你可以在下面看到它:

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

所以我试图从游戏中心的排行榜上获得最高分。我希望我的方法在收到分数后返回分数,但它不返回我的分数。

在块中,它识别分数,在这种情况下为 42,但是一旦我们到达块之外并想要返回它的值 0。

4

3 回答 3

4

两者都loadLeaderboardsWithCompletionHandler异步loadScoresWithCompletionHandler工作。从 文档中:

调用此方法时,它会创建一个新的后台任务来处理请求。然后该方法将控制权返回给您的游戏。稍后,当任务完成时,Game Kit 会调用您的完成处理程序。...

这意味着

[GKLeaderboard loadLeaderboardsWithCompletionHandler:...]

globalRecord在完成块中赋值之前返回。

于 2013-07-01T12:43:39.653 回答
2

您得到的结果为零,因为在块执行之前实际上调用了返回。要获取值,您应该在块结束globalRecord后使用回调:loadScoresWithCompletionHandler

-(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
}
于 2013-07-01T12:46:35.273 回答
0

例如:

-(NSInteger)globalRecord
{
    __block NSInteger globalRecord = 0;

     dispatch_semaphore_t sema = dispatch_semaphore_create(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;
                dispatch_semaphore_signal(sema);
            }

        }];
    }];

    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    dispatch_release(sema);
    //42 here

    return globalRecord;
}

当心!

此示例将阻塞调用此方法的线程

于 2013-07-01T12:54:03.837 回答