Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Foundation
- import CoreData
- class CoreDataStack: NSObject {
- let moduleName = "not"
- let appGroup = "group.com.etherpunk.NotI"
- let databaseName = "NotI"
- func saveToMainContext() { // Just a helper method for removing boilerplate code when you want to save. Remember this will be done on the main thread if called.
- if objectContext.hasChanges {
- do {
- try objectContext.save()
- } catch {
- print("Error saving main ManagedObjectContext: \(error)")
- }
- }
- }
- lazy var persistentContainer: NSPersistentContainer = {
- let persistentContainer = NSPersistentContainer(name: moduleName)
- let storeURL = URL.storeURL(for: appGroup, databaseName: databaseName)
- let storeDescription = NSPersistentStoreDescription(url: storeURL)
- persistentContainer.persistentStoreDescriptions = [storeDescription]
- persistentContainer.loadPersistentStores(completionHandler: { (storeDescription, error) in
- if let error = error as NSError? {
- // Replace this implementation with code to handle the error appropriately.
- // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
- fatalError("Unresolved error \(error), \(error.userInfo)")
- }
- })
- return persistentContainer
- }()
- lazy var objectContext: NSManagedObjectContext = {
- //let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) // As stated in the documentation change this depending on your need, but i recommend sticking to main thread if possible. Do I realllly need to do this thought? Probably. Need to figure this out.
- let context = self.persistentContainer.viewContext
- return context
- }()
- }
- public extension URL {
- static func storeURL(for appGroup: String, databaseName: String) -> URL {
- guard let fileContainer = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else {
- fatalError("Shared file container could not be created.")
- }
- return fileContainer.appendingPathComponent("\(databaseName).sqlite")
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement