Skip to content

Instantly share code, notes, and snippets.

@vamsiac
Forked from capttaco/Fetchable.swift
Last active May 2, 2017 13:23
Show Gist options
  • Save vamsiac/e975a26433c96a27cb51be9a7a90ae98 to your computer and use it in GitHub Desktop.
Save vamsiac/e975a26433c96a27cb51be9a7a90ae98 to your computer and use it in GitHub Desktop.
A utility protocol for custom NSManagedObjects that makes querying contexts simpler and more convenient. Requires Swift 2.
import CoreData
protocol Fetchable
{
associatedtype FetchableType: NSManagedObject = Self
static func entityName() -> String
static func objectsInContext(_ context: NSManagedObjectContext, predicate: NSPredicate?, sortedBy: String?, ascending: Bool) throws -> [FetchableType]
static func singleObjectInContext(_ context: NSManagedObjectContext, predicate: NSPredicate?, sortedBy: String?, ascending: Bool) throws -> FetchableType?
static func objectCountInContext(_ context: NSManagedObjectContext, predicate: NSPredicate?) -> Int
static func fetchRequest(_ context: NSManagedObjectContext, predicate: NSPredicate?, sortedBy: String?, ascending: Bool) -> NSFetchRequest<NSManagedObject>
}
extension Fetchable where Self : NSManagedObject, FetchableType == Self
{
static func singleObjectInContext(_ context: NSManagedObjectContext, predicate: NSPredicate? = nil, sortedBy: String? = nil, ascending: Bool = false) throws -> FetchableType?
{
let managedObjects: [FetchableType] = try objectsInContext(context, predicate: predicate, sortedBy: sortedBy, ascending: ascending)
guard managedObjects.count > 0 else { return nil }
return managedObjects.first
}
static func objectCountInContext(_ context: NSManagedObjectContext, predicate: NSPredicate? = nil) -> Int
{
let request = fetchRequest(context, predicate: predicate)
var count: Int = 0
do {
count = try context.count(for: request)
} catch {
return 0
}
return count;
}
static func objectsInContext(_ context: NSManagedObjectContext, predicate: NSPredicate? = nil, sortedBy: String? = nil, ascending: Bool = false) throws -> [FetchableType]
{
let request = fetchRequest(context, predicate: predicate, sortedBy: sortedBy, ascending: ascending)
let fetchResults = try context.fetch(request)
return fetchResults as! [FetchableType]
}
static func fetchRequest(_ context: NSManagedObjectContext, predicate: NSPredicate? = nil, sortedBy: String? = nil, ascending: Bool = false) -> NSFetchRequest<NSManagedObject>
{
let request = NSFetchRequest<NSFetchRequestResult>()
let entity = NSEntityDescription.entity(forEntityName: entityName(), in: context)
request.entity = entity
if predicate != nil {
request.predicate = predicate
}
if (sortedBy != nil) {
let sort = NSSortDescriptor(key: sortedBy, ascending: ascending)
let sortDescriptors = [sort]
request.sortDescriptors = sortDescriptors
}
return request as! NSFetchRequest<NSManagedObject>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment