Skip to content

Instantly share code, notes, and snippets.

@thepost
Created December 4, 2018 03:52
Show Gist options
  • Save thepost/74d72fdba11f155b04d8786fb00d75ca to your computer and use it in GitHub Desktop.
Save thepost/74d72fdba11f155b04d8786fb00d75ca to your computer and use it in GitHub Desktop.
extension ModelController {
func total<M: NSManagedObject>(_ type: M.Type) -> Int {
let entityName = String(describing: type)
let request = NSFetchRequest<M>(entityName: entityName)
do {
let count = try context.count(for: request)
return count
}
catch {
print("Error executing total: \(error)")
return 0
}
}
func fetch<M: NSManagedObject>(_ type: M.Type, predicate: NSPredicate?=nil, sort: NSSortDescriptor?=nil) -> [M]? {
var fetched: [M]?
let entityName = String(describing: type)
let request = NSFetchRequest<M>(entityName: entityName)
request.predicate = predicate
request.sortDescriptors = [sort] as? [NSSortDescriptor]
do {
fetched = try context.fetch(request)
}
catch {
print("Error executing fetch: \(error)")
}
return fetched
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment