Advertisement
Nazadus

Untitled

Jan 29th, 2020
313
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.36 KB | None | 0 0
  1. import Foundation
  2. import CoreData
  3.  
  4. class CoreDataStack: NSObject {
  5.     let moduleName = "not"
  6.     let appGroup = "group.com.etherpunk.NotI"
  7.     let databaseName = "NotI"
  8.  
  9.     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.
  10.         if objectContext.hasChanges {
  11.             do {
  12.                 try objectContext.save()
  13.             } catch {
  14.                 print("Error saving main ManagedObjectContext: \(error)")
  15.             }
  16.         }
  17.     }
  18.  
  19.     lazy var persistentContainer: NSPersistentContainer = {
  20.         let persistentContainer = NSPersistentContainer(name: moduleName)
  21.         let storeURL = URL.storeURL(for: appGroup, databaseName: databaseName)
  22.         let storeDescription = NSPersistentStoreDescription(url: storeURL)
  23.         persistentContainer.persistentStoreDescriptions = [storeDescription]
  24.         persistentContainer.loadPersistentStores(completionHandler: { (storeDescription, error) in
  25.             if let error = error as NSError? {
  26.                 // Replace this implementation with code to handle the error appropriately.
  27.                 // 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.
  28.  
  29.                 fatalError("Unresolved error \(error), \(error.userInfo)")
  30.             }
  31.         })
  32.        
  33.         return persistentContainer
  34.     }()
  35.  
  36.  
  37.     lazy var objectContext: NSManagedObjectContext = {
  38.         //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.
  39.        
  40.         let context = self.persistentContainer.viewContext
  41.         return context
  42.     }()
  43. }
  44.  
  45. public extension URL {
  46.     static func storeURL(for appGroup: String, databaseName: String) -> URL {
  47.         guard let fileContainer = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else {
  48.             fatalError("Shared file container could not be created.")
  49.         }
  50.        
  51.         return fileContainer.appendingPathComponent("\(databaseName).sqlite")
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement