从块返回整数

时间:2013-07-01 12:38:59

标签: iphone ios objective-c block game-center

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

-(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。

3 个答案:

答案 0 :(得分:4)

loadLeaderboardsWithCompletionHandlerloadScoresWithCompletionHandler都是异步工作的。来自 documentation

  

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

这意味着

[GKLeaderboard loadLeaderboardsWithCompletionHandler:...]

在完成块中将值分配给globalRecord之前返回。

答案 1 :(得分: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
}

答案 2 :(得分: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;
}

小心!

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