2 guodeganggdg guodegangGDG 于 2013.07.02 10:45 提问

iphone-从block中返回整数

要从调用的block中返回整数:

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

从游戏中心的排行榜返回最高分,需求是只要接收到分数方法就返回给我,但是没返回成功。

比如在block中最高分是42,但是在block外值就是0。

请高手帮忙解答。

2个回答

prettYYoyic
prettYYoyic   2013.07.02 16:07
已采纳

要获取globalRecord值应该使用一个回调。

-(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
}
zhanglei5415
zhanglei5415   Rxr 2013.07.02 11:02

请参见我先前的回答,你的问题同  等待AFJSONRequestOperation完成

要解决你的问题,也很简单,需要重新修改一下你的globalRecord方法,改成无返回值的方法

-(void)globalRecordWithBlock:(void(^)(int record))processResult
{
    __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
            }
            processResult(globalRecord);  ///将结果回调给调用者
        }];
    }];

}

调用:

[obj globalRecordWithBlock^(int record) {
       NSLog(@"global record is :%d",record);
}];
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!