title: Is NSUserDefaults threadsafe
body: <p>I know that documentation says that it is, and i know that this subject was already under discussion but I have an interesting stack result and I cant conclude anything else but that <code>[NSUserDefaults standardUserDefaults]</code> is not threadsafe. So I will post my crash log and hope that somebody sees something that I can't...</p>
  
  <p>Crashed Thread</p>
  
  <pre><code>    ... 
      libdispatch.dylib 0x3ab53d67 _dispatch_client_callout + 23
      libdispatch.dylib 0x3ab65e73 _dispatch_barrier_sync_f_invoke + 27
      CoreFoundation 0x302b470d CFPreferencesAppSynchronize + 265       
      Foundation 0x30151b01 -[NSUserDefaults(NSUserDefaults) synchronize] + 25
      MyApp 0x0009df8b -[AppDelegate applicationDidEnterBackground:] (AppDelegate.m:178)
      ...
      MyApp 0x0005344b main (main.m:17)
      MyApp 0x000533f8 start + 40
  </code></pre>
  
  <p>some other thread</p>
  
  <pre><code>    ...
      CoreFoundation 0x302bc13f _CFXPreferencesSetValue + 107
      CoreFoundation 0x302bc039 CFPreferencesSetAppValue + 41
      Foundation 0x30c76935 -[NSUserDefaults(NSUserDefaults) setObject:forKey:] + 61
      MyApp 0x000b2e9d -[AppData parserDidEndDocument:] (AppData.m:1013)
     ...
  </code></pre>
  
  <p>Parts of the stack have been cut out and substituted with "..." cause its just too long and irrelevant for the subject. App crashes with message:</p>
  
  <blockquote>
    <p><em>*</em> Collection &lt;__NSDictionaryM: 0x15a04ae0> was mutated while being enumerated.
    ....</p>
  </blockquote>
  
  <p>Code: 
  AppDelegate: -> crached thread...</p>
  
  <pre><code>    - (void)applicationDidEnterBackground:(UIApplication *)application
      {
          [[NSUserDefaults standardUserDefaults] synchronize];
      }
  </code></pre>
  
  <p>MyClass: ->second thread:</p>
  
  <pre><code>    -(void)parserDidEndDocument:(NSXMLParser *)parser {
      ...
          [[NSUserDefaults standardUserDefaults] setObject:arr forKey:@"savedStations"];
          [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"lastUpdateDate"];
          [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"alreadyLoaded"];
      ...
      }
  </code></pre>
  
  <p>I have this crash in couple of other cases, it always includes some writing to user defaults in one thread and synchronizeing in other thread that crashes.. If anyone has some other explanation I would be very greatfull... </p>