Skip to content

Commit

Permalink
Update logging to log warnings for saving in main context
Browse files Browse the repository at this point in the history
  • Loading branch information
itsmeichigo committed Oct 3, 2024
1 parent 6d902d8 commit 95135b9
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions Storage/Storage/Extensions/NSManagedObjectContext+Storage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,9 @@ extension NSManagedObjectContext: StorageType {
return
}

/// cannot infer the entity name here, so leaving it empty
Self.ensureCorrectContextUsageIfNeeded(for: "")

do {
try save()
} catch {
Expand Down Expand Up @@ -183,13 +186,19 @@ extension NSManagedObjectContext: StorageType {
///
private static func ensureCorrectContextUsageIfNeeded(for entityName: String) {
#if DEBUG
let enforceWriteInBackground = ProcessInfo.processInfo.arguments.contains("-enforce-core-data-write-in-background")
if enforceWriteInBackground {
assert(Thread.isMainThread == false,
"Write operations for \(entityName) should only be done on a background context")
} else if Thread.isMainThread {
DDLogWarn("⚠️ Write operations for \(entityName) should only be done on a background context ⚠️")
guard Thread.isMainThread else {
return
}
let message: String = {
if entityName.isEmpty {
"⚠️ Saving data should only be done on a background context"
} else {
"⚠️ Write operations for \(entityName) should only be done on a background context"
}
}()

let enforceWriteInBackground = ProcessInfo.processInfo.arguments.contains("-enforce-core-data-write-in-background")
enforceWriteInBackground ? assertionFailure(message) : DDLogWarn(message)
#endif
}
}

0 comments on commit 95135b9

Please sign in to comment.