Skip to content

Commit

Permalink
Use a single background context.
Browse files Browse the repository at this point in the history
  • Loading branch information
jaredsinclair committed Dec 31, 2019
1 parent 1e57ede commit ae594a9
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
2 changes: 1 addition & 1 deletion Package.resolved
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"repositoryURL": "https://github.com/jaredsinclair/etcetera.git",
"state": {
"branch": "spm",
"revision": "88b6533ddce800ef46cb07e8db5fc18d804f8c96",
"revision": "4ec9ca6978c4156980c706a2b908c32e917a1950",
"version": null
}
}
Expand Down
20 changes: 17 additions & 3 deletions Sources/FuckShitStack/FuckShitStack.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,18 @@ public class FuckShitStack {

private let container: NSPersistentContainer
private let backgroundQueue: OperationQueue
private var _backgroundContext = Protected<NSManagedObjectContext?>(nil)

private var backgroundContext: NSManagedObjectContext {
assert(backgroundQueue.isCurrent)
return _backgroundContext.access { context -> NSManagedObjectContext in
if context == nil {
context = container.newBackgroundContext()
context!.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
}
return context!
}
}

// MARK: Factory / Init

Expand Down Expand Up @@ -132,6 +144,8 @@ public class FuckShitStack {
if let error = error {
handler(.failure(error))
} else {
container.viewContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy
container.viewContext.automaticallyMergesChangesFromParent = true
let stack = FuckShitStack(container: container)
handler(.success(stack))
}
Expand Down Expand Up @@ -207,7 +221,7 @@ public class FuckShitStack {
let task = BackgroundTask.start()
let op = BlockOperation { [weak self] in
guard let this = self else { return }
let context = this.container.newBackgroundContext()
let context = this.backgroundContext
context.performAndWait {
block(context)
if saveAfterward {
Expand All @@ -227,8 +241,8 @@ public class FuckShitStack {
public func sync_performInBackground(_ block: @escaping (NSManagedObjectContext) -> Void) {
let op = BlockOperation { [weak self] in
guard let this = self else { return }
let context = this.container.newBackgroundContext()
context.performAndWait {
let context = this.backgroundContext
this.backgroundContext.performAndWait {
block(context)
}
}
Expand Down

0 comments on commit ae594a9

Please sign in to comment.