Note that there are some explanatory texts on larger screens.

plurals
  1. POModifying mutable object in completion handler
    primarykey
    data
    text
    <p>I have a question about thread safety of the following code example from Apple (from GameKit programming guide)</p> <p>This is to load achievements from game center and save it locally:</p> <p>Step 1) Add a mutable dictionary property to your class that report achievements. This dictionary stores the collection of achievement objects.</p> <pre><code>@property(nonatomic, retain) NSMutableDictionary *achievementsDictionary; </code></pre> <p>Step 2) Initialize the achievements dictionary.</p> <pre><code>achievementsDictionary = [[NSMutableDictionary alloc] init]; </code></pre> <p>Step 3) Modify your code that loads loads achievement data to add the achievement objects to the dictionary.</p> <pre><code>{ [GKAchievement loadAchievementsWithCompletionHandler:^(NSArray *achievements, NSError *error) { if (error == nil) { for (GKAchievement* achievement in achievements) [achievementsDictionary setObject: achievement forKey: achievement.identifier]; } }]; </code></pre> <p>My question is as follows - achievementsDictionary object is being modified in the completion handler, without any locks of sort. Is this allowed because completion handlers are a block of work that will be guaranteed by iOS to be executed as unit on the main thread? And never run into thread safety issues?</p> <p>In another Apple sample code (GKTapper), this part is handled differently:</p> <pre><code>@property (retain) NSMutableDictionary* earnedAchievementCache; // note this is atomic </code></pre> <p>Then in the handler:</p> <pre><code>[GKAchievement loadAchievementsWithCompletionHandler: ^(NSArray *scores, NSError *error) { if(error == NULL) { NSMutableDictionary* tempCache= [NSMutableDictionary dictionaryWithCapacity: [scores count]]; for (GKAchievement* score in scores) { [tempCache setObject: score forKey: score.identifier]; } self.earnedAchievementCache= tempCache; } }]; </code></pre> <p>So why the different style, and is one way more correct than the other?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload