Last active
August 29, 2015 14:06
-
-
Save muukii/4c6322afdfe24e6adf96 to your computer and use it in GitHub Desktop.
Swift NSFetchedResultsController
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
var fetchedResultsController: NSFetchedResultsController { | |
if _fetchedResultsController != nil { | |
return _fetchedResultsController! | |
} | |
let fetchRequest = NSFetchRequest() | |
// Edit the entity name as appropriate. | |
let entity = NSEntityDescription.entityForName(CPCommentObject.entityName(), inManagedObjectContext: NSManagedObjectContext.managedObjectContextForMainThread()) | |
fetchRequest.entity = entity | |
// Set the batch size to a suitable number. | |
fetchRequest.fetchBatchSize = 20 | |
// Edit the sort key as appropriate. | |
let sortDescriptor = NSSortDescriptor(key: "date", ascending: false) | |
let sortDescriptors = [sortDescriptor] | |
fetchRequest.sortDescriptors = [sortDescriptor] | |
// Edit the section name key path and cache name if appropriate. | |
// nil for section name key path means "no sections". | |
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: NSManagedObjectContext.managedObjectContextForMainThread(), sectionNameKeyPath: nil, cacheName: nil) | |
aFetchedResultsController.delegate = self | |
_fetchedResultsController = aFetchedResultsController | |
var error: NSError? = nil | |
if !_fetchedResultsController!.performFetch(&error) { | |
// Replace this implementation with code to handle the error appropriately. | |
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. | |
//println("Unresolved error \(error), \(error.userInfo)") | |
abort() | |
} | |
return _fetchedResultsController! | |
} | |
var _fetchedResultsController: NSFetchedResultsController? = nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment