title: Thread safety crash using NSDictionary?
body: <p>I have code accessing and setting an NSDictionary many times across multiple threads, like so:</p>
  
  <pre><code>- (BOOL)flagForItem:(NSNumber*)itemID
  {
      if(itemID) {
          return [[_itemFlagDict objectForKey:itemID] boolValue] 
      }
      return NO;
  } 
  </code></pre>
  
  <p>and:</p>
  
  <pre><code>- (void)setFlagForItem:(NSNumber*)itemID
  {
      if(itemID) {
          NSMutableDictionary *copy = [_itemFlagDict mutableCopy];
          [copy setObject:[NSNumber numberWithBool:YES] forKey:itemID];
          _itemFlagDict = [NSDictionary dictionaryWithDictionary:copy];
      }
  }
  </code></pre>
  
  <p>In the set method, I originally had a NSMutableDictionary - this was changed to the pattern you see now because, doh, NSMutableDictionary isn't threadsafe. My reasoning was to perform the mutation in a copy, and then reassign the <code>_itemFlagDict</code> to capture the update. </p>
  
  <p>However, occasionally a <code>EXC_BAD_ACCESS</code> crash still occurs when accessing the <code>_itemFlagDict</code>, leading me to believe that the dictionary is reassigned WHILE the accessing the <code>objectForKey:itemID</code>. </p>
  
  <p>One other approach I tried was to use <code>@synchronized(_itemFlagDict)</code> on both the accessor and the setter methods. While this fixed the issue, this code is performance sensitive and synchronizing the access/assignment caused too much performance degradation. </p>
  
  <p>So my question is, are there other patterns/methods I can use to avoid this bad access while not compromising performance? If prioritization matters, the execution (and not necessarily iron-clad accuracy) of the accessor method is most important. </p>
  
  <p>Note: i'm working with iOS 4 and above</p>