title: Objective-C: How do I modify the NSMutableArray in a different thread safely?
body: <p>I declared a atomic NSMutableArray to save objects</p>
  
  <pre><code>@property (atomic, strong) NSMutableArray *list;
  @synthesize list;
  </code></pre>
  
  <p>Then I'm using a thread to save object like:</p>
  
  <pre><code>__weak typeof(self) weakSelf = self;
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ // writing files into the disk in background
      // do something..
  
      [weakSelf.list addObject:object]; // add object at the end of the list
  
      if (!weakSelf.threadCreateFlag) {
          NSInvocationOperation *newoperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(createThreadMethod) object:nil]; // create thread to remove from the array
  
          [weakSelf.serailQueue addOperation:newoperation];
      }
  });
  </code></pre>
  
  <p>And I'm trying to read the object at index 0 and remove it from the array</p>
  
  <pre><code>- (void)createThreadMethod {
  
  self.threadCreateFlag = YES;
  
  do {
      NSLog(@"loop");
      @autoreleasepool {
  
          NSDictionary *object = (NSDictionary *)[self.list objectAtIndex:0];
          [self.list removeObjectAtIndex:0];
  
          // doing something...
      }
  } while(self.list.count &gt; 0);
  
  self.photoSavingLock = NO;
  }
  </code></pre>
  
  <p>I am confronted with an issue - sometimes, the array contains object 0x0, and my app will crash.
  I did some research about it, I think because <code>removeObjectAtIndex</code> is not thread-safe. So I'm trying to add a global <code>@property (atomic, strong) NSLock *lock</code> around read/remove and add function.
  But this time I got <code>[NSLock deadlock]</code>.</p>
  
  <p>What is the proper way to make this scenario thread-safe?</p>