NSPersistentContainer equivalent for NSPersistentStoreCoordinator.addPersistentStore ofType and options
Asked Answered
C

2

13

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?

Connate answered 9/3, 2017 at 10:51 Comment(0)
E
18
let description = NSPersistentStoreDescription()
description.shouldInferMappingModelAutomatically = true
description.shouldMigrateStoreAutomatically = true
description.setOption(FileProtectionType.complete, forKey: NSPersistentStoreFileProtectionKey)
container.persistentStoreDescriptions = [description]
Eda answered 9/3, 2017 at 10:55 Comment(2)
You should get the URL of the persister though to create your store description: let storeURL = container.persistentStoreDescriptions.first!.url! let description = NSPersistentStoreDescription(url: storeURL)Predestination
The compiler complained about FileProtectionType.complete and asked me to cast to NSObject Is this OK? description.setOption(FileProtectionType.complete as NSObject, forKey: NSPersistentStoreFileProtectionKey)Filamentary
K
4

(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 ... }
Kiger answered 13/11, 2020 at 2:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.