Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
extension ManagedObjectConvertible where T: ObjectConvertible, Self: NSManagedObject {
var identifier: String? {
return objectID.uriRepresentation().absoluteString
}
static func insert(_ object: T, with context: NSManagedObjectContext) {
guard object.identifier == nil else { return }
let managedObject = Self(context: context)
managedObject.from(object: object)
try? context.save()
}
static func update(_ object: T, with context: NSManagedObjectContext) {
guard let managedObject = get(object: object, with: context) else {
return
}
managedObject.from(object: object)
try? context.save()
}
static func delete(_ object: T, with context: NSManagedObjectContext) {
guard let managedObject = get(object: object, with: context) else {
return
}
context.delete(managedObject)
try? context.save()
}
static func fetchAll(from context: NSManagedObjectContext) -> [T] {
let request = NSFetchRequest<Self>(entityName: String(describing: self))
request.returnsObjectsAsFaults = false
do {
let managedObjects = try context.fetch(request)
return managedObjects.map { $0.toObject() }
} catch {
return [T]()
}
}
private static func get(object: T, with context: NSManagedObjectContext) -> Self? {
guard
let identifier = object.identifier,
let uri = URL(string: identifier),
let objectID = context.persistentStoreCoordinator?.managedObjectID(forURIRepresentation: uri) else
{
return nil
}
do {
return try context.existingObject(with: objectID) as? Self
} catch {
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment