Skip to content

Instantly share code, notes, and snippets.

@hmlongco
Last active October 12, 2022 18:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hmlongco/168deb56c864092c927329aca8d9e420 to your computer and use it in GitHub Desktop.
Save hmlongco/168deb56c864092c927329aca8d9e420 to your computer and use it in GitHub Desktop.
Core Data Extensions for SwiftUI
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