John Doe
John Doe

Reputation: 1414

How to configure In-Memory database when testing?

I have checked some websites from apple, most appear to be outdated and lacking because I needed convert the code after pasting them into XCode8. I have an old code but I can't figure out how to migrate them to the new style.

Here is my old code:

    self.psc = {
    let psc = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)

    do {
        _ = try psc.addPersistentStore(
         ofType: NSInMemoryStoreType, configurationName: nil,
        at: nil, options: nil)
    } catch {
    fatalError()
}

return psc

Here is what I have done so far,

    lazy var testPersistentContainer: NSPersistentContainer = {
    let container = NSPersistentContainer(name: "Test Data Store")

    do {
        try container.persistentStoreCoordinator.addPersistentStore(ofType:
            NSInMemoryStoreType, configurationName: "Test Persistent Store",
                                 at: nil, options: [:])
    } catch {
        let nserror = error as NSError
        fatalError("Unresolved error \(error), \(nserror.userInfo)")
    }

There is exception in the try statement.

Error Domain=Foundation._GenericObjCError Code=0 "(null)" fatal error: Unresolved error nilError

Upvotes: 0

Views: 820

Answers (1)

Ketan P
Ketan P

Reputation: 4379

You can continue using the old approach. It's not deprecated, and NSPersistentContainer isn't required.

If you want the newer approach, use the new NSPersistentStoreDescription class, which handles all the stuff that could be specified when adding a persistent store.

You can try below code for newer approach :

lazy var persistentContainer: NSPersistentContainer = {
            let container = NSPersistentContainer(name: "DataModel")

            // Need to add NSPersistentStoreDescription ===
            let description = NSPersistentStoreDescription()
            description.type = NSInMemoryStoreType
            container.persistentStoreDescriptions = [description]

            container.loadPersistentStores(completionHandler: { [weak self](storeDescription, error) in
                if let error = error {
                    NSLog("CoreData error \(error), \(error._userInfo)")
                    self?.errorHandler(error)
                }
                })
            return container
        }()

Hope this help you.

Upvotes: 4

Related Questions