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
?
(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 ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With