Xcode 12 CoreData Template

I'd love some help trying to understand the CoreDate template that you get when you create a new multiplatform app in Xcode 12 (beta 6 fwiw).

In particular, I want to better understand what is happening in the initializer for the PersistenceController:

Code Block
init(inMemory: Bool = false) {
container = NSPersistentContainer(name: "CoreDataTest2")
        if inMemory {
            container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
        }
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
    }

In particular, I'm wondering about two things:
  1. What purpose does the inMemory Bool serve? It's set to true when the template uses the SwiftUI preview, but when else would you set it to true? When would you set it to false?

  2. When it is set to true it then creates the persistent store description to a file URL with path "/dev/null" -- what does this mean? Do we need to set the Persistent Store Description to something else in production code?

Hi Ryan,

I know it's been quite a while with no answer but I'll answer for future readers!

What purpose does the inMemory Bool serve?

It simply allows you to set your persistent store to a temporary location that gets wiped out after it's used so your persistent store is not persistent.

You see, normally the store of data will persist on the drive (hardware) of a device. If you run your app and expand your persistentContainer in Xcode's Variables View, such as: _storeDescriptions > [0] > _url, you'll see this long path where the persistent store is actually located.

But when inMemory is set to true, the _url value is just file:///dev/null

When else would you set it to true?

Only when you're testing and you want to create/save/update/delete data and not have it persist once the app stops running. So definitely don't set to true when releasing to the App Store. 😃

When would you set it to false?

When you deploy your app to TestFlight or to the App Store or when you want to do further testing that requires your data to persist after your app shuts down.

When it is set to true it then creates the persistent store description to a file URL with path "/dev/null" -- what does this mean?

This is a special place that does NOT persist and will vanish once your app stops running.

The full URL is: file:///dev/null

This is kind of a "secret place". It's so secret that you can't find it on your hard drive, even when you show hidden files. The only way I can see this location is by taking that URL and putting it in Chrome (Safar won't show it).

Do we need to set the Persistent Store Description to something else in production code?

Nope. Your app will know where to put it.

Hope this helps!

Xcode 12 CoreData Template
 
 
Q