Skip to content

Instantly share code, notes, and snippets.

@qubblr
Last active October 27, 2016 09:49
Show Gist options
  • Save qubblr/540ddadb38387df7c649910ebadcbdbd to your computer and use it in GitHub Desktop.
Save qubblr/540ddadb38387df7c649910ebadcbdbd to your computer and use it in GitHub Desktop.
CoreData Stack (2 MOC setup)
import CoreData
class CoreDataStack {
static let instance = CoreDataStack(storeName: "STORE_NAME")
public let privateContext: NSManagedObjectContext
public let mainContext: NSManagedObjectContext
let objectModel: NSManagedObjectModel
let storeCoordinator: NSPersistentStoreCoordinator
init(storeName: String) {
objectModel = NSManagedObjectModel.mergedModel(from: nil)!
storeCoordinator = NSPersistentStoreCoordinator(managedObjectModel: objectModel)
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last
let storeUrl = documentsDirectory?.appendingPathComponent(storeName + ".sqlite")
let options = [NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true]
do {
try storeCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeUrl, options: options)
} catch let error as NSError {
print("Persistent store error: \(error.localizedDescription)")
}
privateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
privateContext.persistentStoreCoordinator = storeCoordinator
mainContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
mainContext.persistentStoreCoordinator = storeCoordinator
NotificationCenter.default.addObserver(forName: NSNotification.Name.NSManagedObjectContextDidSave, object: nil, queue: nil) {
notification in
if let moc = notification.object as? NSManagedObjectContext {
if moc !== self.mainContext {
self.mainContext.mergeChanges(fromContextDidSave: notification)
}
}
}
}
public class func setup() {
_ = CoreDataStack.instance
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment