Last active
October 12, 2015 16:03
-
-
Save mingsai/34b856f068ad428f16cb 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
//Source (http://christiantietze.de/posts/2015/10/results-from-fetch-requests/) | |
import Foundation | |
import CoreData | |
enum CoreDataError: ErrorType { | |
case InconsistentCoreDataFetchRequestResults | |
} | |
class CoreDataFetchRequest<T: NSManagedObject> { | |
let fetchRequest: NSFetchRequest | |
var predicate: NSPredicate? { | |
get { return fetchRequest.predicate } | |
set { fetchRequest.predicate = newValue } | |
} | |
convenience init(entityName: String) { | |
self.init(fetchRequest: NSFetchRequest(entityName: entityName)) | |
} | |
init(fetchRequest: NSFetchRequest) { | |
self.fetchRequest = fetchRequest | |
} | |
func executeInContext(context: NSManagedObjectContext) throws -> [T] { | |
let results = try context.executeFetchRequest(fetchRequest) | |
guard let properResults = results as? [T] else { | |
throw CoreDataError.InconsistentCoreDataFetchRequestResults | |
} | |
return properResults | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment