guodegangGDG
2013-07-02 02:45
采纳率: 74.1%
浏览 3.9k
已采纳

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 2013-07-02 08: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
    }
    
    点赞 评论
  • ReyZhang 2013-07-02 03: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);
    }];
    
    点赞 评论

相关推荐 更多相似问题