Last active
October 30, 2019 14:21
-
-
Save sisoje/b7466e1009351f78a56644e53830983b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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