Created
December 4, 2018 03:52
-
-
Save thepost/74d72fdba11f155b04d8786fb00d75ca 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 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