Last active
October 12, 2022 18:05
-
-
Save hmlongco/168deb56c864092c927329aca8d9e420 to your computer and use it in GitHub Desktop.
Core Data Extensions for SwiftUI
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
class RingEditViewModel: ObservableObject { | |
@NestedObservableObject var ring: RingData | |
private let isEditing: Bool | |
private let temporaryContext: NSManagedObjectContext | |
init(context: NSManagedObjectContext, ring: RingData? = nil) { | |
self.temporaryContext = context.child() | |
if let ring = temporaryContext.copy(of: ring) { | |
self.ring = ring | |
self.isEditing = true | |
} else { | |
self.ring = temporaryContext.instance() | |
self.isEditing = false | |
} | |
} | |
var pageTitle: String { | |
isEditing ? "Edit Ring" : "Add Ring" | |
} | |
var saveButtonTitle: String { | |
isEditing ? "Save Changes" : "Add Ring" | |
} | |
func persist() { | |
try? ring.persist() | |
} | |
} | |
extension NSManagedObjectContext { | |
func child() -> NSManagedObjectContext { | |
let child = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) | |
child.parent = self | |
return child | |
} | |
func copy<T:NSManagedObject>(of object: T?) -> T? { | |
guard let object, let copy = (try? existingObject(with: object.objectID)) as? T else { | |
return nil | |
} | |
return copy | |
} | |
func instance<T:NSManagedObject>() -> T { | |
T(context: self) | |
} | |
} | |
extension NSManagedObject { | |
func persist() throws { | |
if hasChanges { | |
try managedObjectContext?.save() | |
try managedObjectContext?.parent?.save() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment