Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPersistentContainer equivalent for NSPersistentStoreCoordinator.addPersistentStore ofType and options

At WWDC2016 Apple introduces NSPersistentContainer for iOS10

The NSPersistentContainer class is in charge of loading the data model, creating a managed object model, and using it to create a NSPersistentStoreCoordinator.

Its initialization is really easy:

let container = NSPersistentContainer(name: "myContainerName")
container.loadPersistentStores(completionHandler: { /* ... handles the error ... */ })

Previously in the CoreData stack creation we set up the NSPersistentStoreCoordinator adding a PersistentStore in particular with "ofType" and "storeOptions"

let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: [NSPersistentStoreFileProtectionKey:FileProtectionType.complete, NSMigratePersistentStoresAutomaticallyOption: true] as [NSObject : AnyObject])

using in this case

NSSQLiteStoreType for ofType parameter

and

[NSPersistentStoreFileProtectionKey:FileProtectionType.complete, NSMigratePersistentStoresAutomaticallyOption: true] for options parameter

How can I configure this kind of stuff using NSPersistentContainer?

like image 262
Giovanni Trezzi Avatar asked Mar 09 '17 10:03

Giovanni Trezzi


1 Answers

(Posting a separate answer since it's too long to be a comment on the last answer)

The following code worked for me:

let container = NSPersistentContainer(name: "MyApp")

let storeDirectory = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
let url = storeDirectory.appendingPathComponent("MyApp.sqlite")
let description = NSPersistentStoreDescription(url: url)
description.shouldInferMappingModelAutomatically = true
description.shouldMigrateStoreAutomatically = true
description.setOption(FileProtectionType.completeUnlessOpen as NSObject, forKey: NSPersistentStoreFileProtectionKey)
container.persistentStoreDescriptions = [description]

container.loadPersistentStores(completionHandler: { (storeDescription, error) in ... }
like image 199
gumbypp Avatar answered Sep 28 '22 02:09

gumbypp