Guest User

Untitled

a guest
Nov 9th, 2018
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.05 KB | None | 0 0
  1. //
  2. // coreDataStorage.swift
  3. // testSCD
  4. //
  5. // Created by Kai Gothe on 19.10.18.
  6. // Copyright © 2018 Kai Gothe. All rights reserved.
  7. //
  8.  
  9. import Foundation
  10. import CoreData
  11.  
  12. open class coreDataStorage {
  13.  
  14. // MARK: - Project Settings
  15.  
  16. let productName = "Appname"
  17. let AppGroup = "APPGroup"
  18.  
  19. // MARK: - Shared Instance
  20.  
  21. public static let sharedInstance = coreDataStorage()
  22.  
  23. // MARK: - Initialization
  24.  
  25. init() {
  26. NotificationCenter.default.addObserver(self, selector: #selector(contextDidSavePrivateQueueContext(_:)), name: NSNotification.Name.NSManagedObjectContextDidSave, object: self.privateQueueCtxt)
  27. NotificationCenter.default.addObserver(self, selector: #selector(contextDidSaveMainQueueContext(_:)), name: NSNotification.Name.NSManagedObjectContextDidSave, object: self.mainQueueCtxt)
  28. }
  29.  
  30. deinit {
  31. NotificationCenter.default.removeObserver(self)
  32. }
  33.  
  34. // MARK: - Notifications
  35.  
  36. @objc func contextDidSavePrivateQueueContext(_ notification: Notification) {
  37. if let context = self.mainQueueCtxt {
  38. self.synced(self, closure: { () -> () in
  39. context.perform({() -> Void in
  40. context.mergeChanges(fromContextDidSave: notification)
  41. })
  42. })
  43. }
  44. }
  45.  
  46. @objc func contextDidSaveMainQueueContext(_ notification: Notification) {
  47. if let context = self.privateQueueCtxt {
  48. self.synced(self, closure: { () -> () in
  49. context.perform({() -> Void in
  50. context.mergeChanges(fromContextDidSave: notification)
  51. })
  52. })
  53. }
  54. }
  55.  
  56. func synced(_ lock: AnyObject, closure: () -> ()) {
  57. objc_sync_enter(lock)
  58. closure()
  59. objc_sync_exit(lock)
  60. }
  61.  
  62. // MARK: - Core Data stack
  63.  
  64. lazy var applicationDocumentsDirectory: URL = {
  65. // The directory the application uses to store the Core Data store file. This code uses a directory named 'Bundle identifier' in the application's documents Application Support directory.
  66. let urls = Foundation.FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
  67. return urls[urls.count-1]
  68. }()
  69.  
  70. lazy var managedObjectModel: NSManagedObjectModel = {
  71. // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
  72. let modelURL = Bundle.main.url(forResource: productName, withExtension: "momd")!
  73. return NSManagedObjectModel(contentsOf: modelURL)!
  74. }()
  75.  
  76. lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
  77. // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
  78. // Create the coordinator and store
  79. var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
  80. let options = [
  81. NSMigratePersistentStoresAutomaticallyOption: true,
  82. NSInferMappingModelAutomaticallyOption: true
  83. ]
  84. let directory = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: AppGroup)!
  85. let url = directory.appendingPathComponent("\(productName).sqlite")
  86. do {
  87. try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options)
  88. } catch var error as NSError {
  89. coordinator = nil
  90. NSLog("Unresolved error \(error), \(error.userInfo)")
  91. abort()
  92. } catch {
  93. fatalError()
  94. }
  95. return coordinator
  96. }()
  97.  
  98. // MARK: - NSManagedObject Contexts
  99.  
  100. open class func mainQueueContext() -> NSManagedObjectContext {
  101. return self.sharedInstance.mainQueueCtxt!
  102. }
  103.  
  104. open class func privateQueueContext() -> NSManagedObjectContext {
  105. return self.sharedInstance.privateQueueCtxt!
  106. }
  107.  
  108. lazy var mainQueueCtxt: NSManagedObjectContext? = {
  109. // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
  110. var managedObjectContext = NSManagedObjectContext(concurrencyType:.mainQueueConcurrencyType)
  111. managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator
  112. return managedObjectContext
  113. }()
  114.  
  115. lazy var privateQueueCtxt: NSManagedObjectContext? = {
  116. // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
  117. var managedObjectContext = NSManagedObjectContext(concurrencyType:.privateQueueConcurrencyType)
  118. managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator
  119. return managedObjectContext
  120. }()
  121.  
  122. // MARK: - Core Data Saving support
  123.  
  124. open class func saveContext(_ context: NSManagedObjectContext?) {
  125. if let moc = context {
  126. if moc.hasChanges {
  127. do {
  128. try moc.save()
  129. } catch {
  130. print(error.localizedDescription)
  131. }
  132. }
  133. }
  134. }
  135.  
  136. }
  137. extension NSManagedObject {
  138.  
  139. public class func findAllForEntity(_ entityName: String, context: NSManagedObjectContext) -> [AnyObject]? {
  140. let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
  141. let result: [AnyObject]?
  142. do {
  143. result = try context.fetch(request)
  144. } catch let error as NSError {
  145. print(error)
  146. result = nil
  147. }
  148. return result
  149. }
  150. }
Add Comment
Please, Sign In to add comment