title: IOS How to sync multithreading NSManagedObjectContext?
body: <p>Application must update data from WebService in loop each 10 sec in background and display data to user by his request in the main thread. Also I need update and delete records by user request.
  Updates done with runloop.</p>
  
  <p>I have registered notification in the AppDelegate</p>
  
  <pre><code> [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contextChanged:) name:NSManagedObjectContextDidSaveNotification object:nil];
  
  - (void)contextChanged:(NSNotification*)notification
  {
      if ([notification object] == [self managedObjectContext]) return;
  
      if (![NSThread isMainThread]) {
          [self performSelectorOnMainThread:@selector(contextChanged:) withObject:notification waitUntilDone:YES];
          return;
      }
  
      [[self managedObjectContext] mergeChangesFromContextDidSaveNotification:notification];
      [self saveContext]; //do I need this here or marge save data too?
  
  }
  </code></pre>
  
  <p>I have Storage sharedInstance class with </p>
  
  <pre><code>NSOperationQueue* operationQueue;
  </code></pre>
  
  <p>then inserts,updates,selects operators added this way from any thread:</p>
  
  <pre><code>-(void)do_something
  {
      [self.operationQueue addOperationWithBlock:^{
      NSManagedObjectContext*moc; //creating new NSManagedObjectContext with AppDelegate.persistentStoreCoordinator 
      //do my staff
      [moc save:&amp;error] 
      }]
  }
  </code></pre>
  
  <p>The problem is when I try update entities with @"my_id=%@", @(my_id)  </p>
  
  <pre><code>[moc countForFetchRequest:fetchRequest error:&amp;error] 
  </code></pre>
  
  <p>return 0 and cause inserting of duplicate exists entity
  The problem is with synchronization.
  Advice please.
  should I use instance of dispatch_queue_create("com.my.", 0); instead  for each CoreData operation?</p>
  
  <hr>
  
  <p>I did try remove operationQuiue</p>
  
  <pre><code>-(void)query:(void(^)(NSManagedObjectContext *context))queryBlock
  {
      NSLog(@"query CALL");
     __block NSManagedObjectContext *context;
      //if remove dispatch_sync and/or run in main thread result the same
      dispatch_sync( dispatch_queue_create("com.myapp.db-queue", 0), ^{
      AppDelegate*app = AppDelegate();
  
      //same result if I use 
      //app.persistentStoreCoordinator or 
      //[app.managedObjectContext persistentStoreCoordinator]
  
      NSPersistentStoreCoordinator *persistentStoreCoordinator= [app.managedObjectContext persistentStoreCoordinator];
  
      context = [NSManagedObjectContext new];
      [context setPersistentStoreCoordinator:persistentStoreCoordinator];
      [context setMergePolicy:NSMergeByPropertyStoreTrumpMergePolicy];
  
      queryBlock(context);
      if ([context hasChanges])
      {
          NSError*err;
          [context save:&amp;err];
          if (err) {
              NSLog(@"context save: %@",[err localizedDescription]);
          }
      }
      });
  }
  </code></pre>
  
  <p>and call it as :</p>
  
  <pre><code>CoreStorage* cs = [CoreStorage sharedInstance];
  NSArray* list = [ws GetSections]; //array of NSDictionaries
  
  //if add this to operationQuiue resunt the same
  [cs query:^(NSManagedObjectContext *moc) {
  NSLog(@"START");
  for (NSDictionary *section in list) {
  
      NSNumber* Id= @([[section objectForKey:@"section_id"] integerValue]);
  
      NSFetchRequest * fetchRequest = [NSFetchRequest new];
      NSEntityDescription *entity = [NSEntityDescription entityForName:@"Section" inManagedObjectContext: moc];
      [fetchRequest setEntity:entity];
      [fetchRequest setFetchLimit:1];
      [fetchRequest setIncludesSubentities:NO];
      [fetchRequest setPredicate: [NSPredicate predicateWithFormat:@"section_id=%@",Id]];
  
      NSError *error =nil;
      Section *entry;
      if ([moc countForFetchRequest:fetchRequest error:&amp;error] &gt;0)
      {
          entry = [moc executeFetchRequest:fetchRequest error:nil][0];
          NSLog(@"exist"); //this never call
      }
      else
      {
          entry = [NSEntityDescription insertNewObjectForEntityForName:@"Section" inManagedObjectContext:moc];
          NSLog(@"NEW");
      }
  
      entry.section_id = Id;
      entry.timeStamp = [NSDate date];
  }
  }];
  </code></pre>
  
  <p>Any sugastions please?</p>