Last active
February 3, 2019 20:50
-
-
Save nicol3a/d03b813c13b3ef319bb7fe21b305b547 to your computer and use it in GitHub Desktop.
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
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