0

My app has a single MOC that is created on the main thread when app is launched. However, I get unexpected behavior (very rarely) where NSManagedObjectContextDidSaveNotification is posted on a background thread while I expect it on the main thread. Here is the code:

  [[NSNotificationCenter defaultCenter] addObserverForName:NSManagedObjectContextDidSaveNotification
                                                      object:self.managedObjectContext
                                                       queue:nil
                                                  usingBlock:^(NSNotification *notification) {
       if (![NSThread isMainThread]) {
          // Rarely getting here, not sure why?
       }
   
  }];

The self.managedObjectContext refers to the MOC instance I create on the main thread when app is loaded.

Any ideas what could be the reason?

Joshua
  • 1,974
  • 2
  • 23
  • 39
  • So sometimes the notification is thrown from a background thread (the normal behavior since you put `queue:nil`) Did you check the stacktrace when it's not the case? Might have some clue. Are you sure that you are saving only in main thread? Do you do the `context.performBlock` or `context.performAndWait`? You might use https://stackoverflow.com/questions/41176098/is-this-a-valid-way-of-debugging-coredata-concurrency-issues to help you track it – Larme Jul 23 '21 at 14:09
  • Additionaly, a common tread error behavior is when you have a block, for instance a WebCall one, and that block isn't called always on the same thread. For instance: `if (!someNeededValue) { block(); return } else doWebCall(block: block)`. The first one might be on the called thread, and the second one on the queue used by the webservice handler... – Larme Jul 23 '21 at 14:12
  • @Larme, thank you for your response. My threading model doesn't allow saving MOC on background thread. For this reason I pass "queue:nil". Also, the issue only happens in production and never while debugging. I probably need to add more logs to Google Analytics to understand who made the change thus violating my threading model. – Joshua Jul 24 '21 at 15:45

0 Answers0