daily pastebin goal
39%
SHARE
TWEET

CoreDataStack.swift

a guest Dec 16th, 2016 160 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import CoreData
  2.  
  3. protocol CoreDataServiceProtocol:class {
  4.     var errorHandler: (Error) -> Void {get set}
  5.     var persistentContainer: NSPersistentContainer {get}
  6.     var managedObjectContext: NSManagedObjectContext {get}
  7.     var backgroundContext: NSManagedObjectContext {get}
  8.     func performBackgroundTask(_ block: @escaping (NSManagedObjectContext) -> Void)
  9.     func performForegroundTask(_ block: @escaping (NSManagedObjectContext) -> Void)
  10. }
  11.  
  12. final class CoreDataStack: CoreDataServiceProtocol {
  13.    
  14.    
  15.        
  16.    
  17.     static let shared = CoreDataStack()
  18.     var errorHandler: (Error) -> Void = {_ in }
  19.    
  20.     lazy var persistentContainer: NSPersistentContainer = {
  21.         let container = NSPersistentContainer(name: "coredatainextension")
  22.        
  23.         container.loadPersistentStores(completionHandler: { (storeDescription, error) in
  24.             if let error = error as NSError? {
  25.             fatalError("Unresolved error (error), (error.userInfo)")
  26.             }
  27.         })
  28.        
  29.        
  30.        
  31.         return container
  32.     }()
  33.    
  34.     lazy var managedObjectContext: NSManagedObjectContext = {
  35.         return self.persistentContainer.viewContext
  36.     }()
  37.    
  38.     lazy var backgroundContext: NSManagedObjectContext = {
  39.         return self.persistentContainer.newBackgroundContext()
  40.     }()
  41.    
  42.     func performForegroundTask(_ block: @escaping (NSManagedObjectContext) -> Void) {
  43.         self.managedObjectContext.perform {
  44.             block(self.managedObjectContext)
  45.         }
  46.     }
  47.    
  48.     func performBackgroundTask(_ block: @escaping (NSManagedObjectContext) -> Void) {
  49.         self.persistentContainer.performBackgroundTask(block)
  50.     }
  51. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top