Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the completionHandler of loadPersistentStores of NSPersistentContainer run synchronously?

Tags:

In Apple's documentation of NSPersistentContainer, the method has the following description:

func loadPersistentStores(completionHandler block: @escaping (NSPersistentStoreDescription, Error?) -> Void)
block: Once the loading of the persistent stores has completed, this block will be executed on the calling thread.

But after many times of debugging the stack trace, I'm pretty sure that the completionHandler is executed synchronously. If I put a print statement after calling loadPersistentStores, it always print after the completionHandler is executed.

So, should I consider when loadPersistentStores returns, the NSPersistentContainer has already loaded (whether successfully or not)?

like image 927
Zhu Shengqi Avatar asked Jul 30 '17 09:07

Zhu Shengqi


1 Answers

This isn't explained clearly anywhere that I can find, but an examination of the documentation leads to some likely answers.

First, NSPersistentStoreDescription has a flag called shouldAddStoreAsynchronously, which defaults to false. If you don't modify your container's descriptions to set the flag, then they're loaded synchronously. That matches what you've seen.

I don't think this is specifically stated for the persistent container option. However the WWDC 2016 "What's New in Core Data" session explains the same thing in the context of NSPersistentStoreCoordinator, with the new (since iOS 10) method addPersistentStore(with:completionHandler:). If you use the async load flag, loading happens asynchronously, otherwise you get the default synchronous load that's been the only option until now.

Based on this I think that what you're seeing is correct: Loading will be synchronous unless you indicate that it should be async. If you set shouldAddStoreAsynchronously to true then I'd expect different behavior. With synchronous loading the completion block is still useful, because that's where errors are reported.

It's also worth remembering that loadPersistentStores may load more than one store, if you add more than one NSPersistentStoreDescription. In that case the completion block may be called more than once.

like image 143
Tom Harrington Avatar answered Oct 23 '22 05:10

Tom Harrington