Skip to content

Instantly share code, notes, and snippets.

@sisoje
Last active October 30, 2019 14:21
Show Gist options
  • Save sisoje/b7466e1009351f78a56644e53830983b to your computer and use it in GitHub Desktop.
Save sisoje/b7466e1009351f78a56644e53830983b to your computer and use it in GitHub Desktop.
import CoreData
public final class CoreDataStack {
public let persistentContainer: NSPersistentContainer
public init(_ persistentContainer: NSPersistentContainer) {
self.persistentContainer = persistentContainer
}
public private(set) lazy var mainContext: NSManagedObjectContext = {
persistentContainer.viewContext.automaticallyMergesChangesFromParent = true
return persistentContainer.viewContext
}()
public private(set) lazy var writingContext = BackgroundManagedObjectContext(persistentContainer) {
$0.automaticallyMergesChangesFromParent = false
}
public private(set) lazy var readingContext = BackgroundManagedObjectContext(persistentContainer) {
$0.automaticallyMergesChangesFromParent = true
}
}
public final class BackgroundManagedObjectContext {
var context: NSManagedObjectContext?
public init(_ container: NSPersistentContainer, _ setup: (NSManagedObjectContext)->Void) {
self.context = container.newBackgroundContext() ~ setup
}
deinit {
context.map {
context = nil
$0.performAndWait {}
}
}
}
public extension BackgroundManagedObjectContext {
func performTask(_ block: @escaping (NSManagedObjectContext) -> Void) {
context?.perform { [weak self] in
self?.context.map {
block($0)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment