iOS-在块内保存数据

时间:2014-07-09 16:19:32

标签: ios objective-c game-center

我已经在这几天苦苦挣扎,所以任何人都会感激不尽。我正在尝试保存下面的播放器阵列并将其显示在UITableView中。我想保存它以便我可以显示本地玩家的朋友。我尝试了几种不同的东西,但看起来它适用于其他人的东西就是这样。

__block NSArray *friends;

- (void) loadPlayerData: (NSArray *) identifiers {
    [GKPlayer loadPlayersForIdentifiers:identifiers withCompletionHandler:^(NSArray *players, NSError *error) {
        if (error != nil) {
            // Handle the error.
        }
        if (players != nil) {
            friends = players;
            NSLog(@"Inside: %@", friends); //Properly shows the array
        }
     }];
    NSLog(@"Outside: %@", friends): //Doesn't work, shows nil
}

但朋友们之后仍然是零/空。难道我做错了什么?有没有办法保存玩家并在UITableView中使用它?感谢。

*** *** EDIT

所以这是我放在一起的解决方案。

typedef void(^CallbackBlock)(id object);

+ (void) retrieveFriends: (CallbackBlock)callback {
    GKLocalPlayer *lp = [GKLocalPlayer localPlayer];

    if (lp.authenticated) {
        [lp loadFriendsWithCompletionHandler:^(NSArray *friends, NSError *error) {
    if (friends != nil) {
        [self loadPlayerDataWithIdentifiers:friends callback:^(NSArray *playersInfo) {
        if (callback) callback(playersInfo);
        }]; 
      }
    }];

  }
}

+ (void) loadPlayerDataWithIdentifiers: (NSArray *) identifiers callback:(CallbackBlock)callback {


  [GKPlayer loadPlayersForIdentifiers:identifiers withCompletionHandler:^(NSArray *players, NSError *error) {
  if (error != nil) {
     // Handle the error.
  }
  if (players != nil) {
     if (callback) callback(players);
  }
  }];
}

唯一的问题是,我的UITableView在另一个类中,所以我尝试这样做并使两个方法公开。 info不打印任何内容。有什么想法吗?

[GameCenterHelper retrieveFriends:^(NSArray *info) {
    NSLog(@"Friends Info: %@", info);
}];

2 个答案:

答案 0 :(得分:0)

使用回调块。

typedef void(^CallbackBlock)(id object);

- (void)loadPlayerDataWithIdentifiers:(NSArray *)identifiers callback:(CallbackBlock)callback {
    [GKPlayer loadPlayersForIdentifiers:identifiers withCompletionHandler:^(NSArray *players, NSError *error) {
        if (error != nil) {
            // Handle the error.
        }
        if (callback) callback(players);
    }];
}

您在问题中暗示这是用于表格视图。如果是这样,您需要在加载数据后重新加载表。

[self loadPlayerDataWithIdentifiers:identifiers callback:^(NSArray *players) {
    self.players = players;
    [self.tableView reloadData];
}];

答案 1 :(得分:0)

Crimson Chris是对的。 另一个选择是使用GCD等待回复的响应。 或者将其更改为同步调用,因为您希望立即获得结果。