title: How do I safely access the contents of an NSArray property from a secondary thread?
body: <p>I have an app (using retain/release, not GC) that maintains an <code>NSArray</code> instance variable, which is exposed as a property like so:</p>
  
  <pre><code>@interface MyObject : NSObject
  {
      NSArray* myArray;
  }
  @property (copy) NSArray* myArray;
  @end
  </code></pre>
  
  <p>I want to access the contents of this array from a secondary thread, which is detached using <code>-performSelectorInBackground:withObject:</code>. It is possible and indeed likely that the array will change during the execution of the secondary thread.</p>
  
  <p>In the secondary thread I want to do something like this:</p>
  
  <pre><code>if([self.myArray containsObject:foo])
  {
      //do stuff
  }
  </code></pre>
  
  <p>From reading the threading documentation, it seems I should be able use the <code>@synchronized</code> directive in the accessors like so:</p>
  
  <pre><code>@implementation MyObject
  - (NSArray *)myArray
  {
      NSArray *result;
      @synchronized(self)
      {
          result = [myArray retain];
      }
      return [result autorelease];
  }
  
  - (void)setMyArray:(NSArray *)aMyArray
  {
      @synchronized(self)
      {
          [myArray release];
          myArray = [aMyArray copy];
      }
  }
  @end
  </code></pre>
  
  <p>Is this all I need to do to ensure thread safety, or is it more complex?</p>
  
  <p><strong>Update:</strong> I've subsequently found a great article on Apple's site that addresses this issue in depth: <a href="http://developer.apple.com/mac/library/technotes/tn2002/tn2059.html" rel="nofollow noreferrer">http://developer.apple.com/mac/library/technotes/tn2002/tn2059.html</a></p>