Skip to content

Instantly share code, notes, and snippets.

@srmds
Created October 2, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save srmds/cdcdb94ac49073f640e2 to your computer and use it in GitHub Desktop.
Save srmds/cdcdb94ac49073f640e2 to your computer and use it in GitHub Desktop.
Swift 2.0 Asynchronous Fetch Request
func getAllEvents(sortedByDate:Bool = false, sortAscending:Bool = true) -> Array<Event> {
print("getAllEvents")
var fetchedResults:Array<Event> = Array<Event>()
let minionManagedObjectContextWorker:NSManagedObjectContext = NSManagedObjectContext.init(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType)
minionManagedObjectContextWorker.parentContext = self.mainContextInstance
let fetchRequest = NSFetchRequest()
let entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: minionManagedObjectContextWorker)
fetchRequest.entity = entity
//Create sort descriptor to sort retrieved Events by Date, ascending
if sortedByDate {
let sortDescriptor = NSSortDescriptor(key: "date",
ascending: sortAscending)
let sortDescriptors = [sortDescriptor]
fetchRequest.sortDescriptors = sortDescriptors
}
let asyncFetch = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) {
(result:NSAsynchronousFetchResult!) -> Void in
if result.finalResult!.count > 0 {
print("async res:\(result.finalResult?.count)")
fetchedResults = result.finalResult! as! [Event]
}
NSLog("Done.\(fetchedResults[0].title)")
}
//Execute Fetch request
minionManagedObjectContextWorker.performBlock {
do {
try minionManagedObjectContextWorker.executeRequest(asyncFetch) as! NSAsynchronousFetchResult
} catch let fetchError as NSError {
print("retrieveById error: \(fetchError.localizedDescription)")
fetchedResults = Array<Event>()
}
}
return fetchedResults
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment