com.iavian
com.iavian

Reputation: 477

GCD - Block - Thread safe variable in loop

Is GKPlayer player is safe inside for loop?

for (GKPlayer *player in players) {
  [player loadPhotoForSize:GKPhotoSizeSmall withCompletionHandler:^(UIImage *photo, NSError *error) {
    if (!error && photo) {
      if ([player.playerID isEqualToString:[GKLocalPlayer localPlayer].playerID]) {
        currentUser.image = photo;
      } else {
        otherUser.image = photo;
      }
    }
  }];
}

Upvotes: 1

Views: 145

Answers (1)

Bryan Chen
Bryan Chen

Reputation: 46598

YES (assuming your code is only executed in main thread)

from Doc

When this method is called, it creates a new background task to handle the request. The method then returns control to your game. Later, when the task is complete, Game Kit calls your completion handler. The completion handler is always called on the main thread.

Your code is only executed in main thread so no thread-safety issue.


A possible execution sequence of your code is something like this

[player1 loadPhotoForSize...];
[player2 loadPhotoForSize...];
[player3 loadPhotoForSize...];

// method return

// photo for player3 downloaded
completionHandlerForPlayer3(photo, error);

// photo for player1 downloaded
completionHandlerForPlayer1(photo, error);

// photo for player1 downloaded
completionHandlerForPlayer2(photo, error);

Everything happened on main thread, it is not possible to have threading issue.

Upvotes: 1

Related Questions