Created
February 26, 2018 10:24
-
-
Save L-Sypniewski/c0b428982ba78d819ad81d66c986abc6 to your computer and use it in GitHub Desktop.
Swift - delete all entities using 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
// Prepare NSFetchedResultsController | |
fileprivate lazy var fetchedResultsController: NSFetchedResultsController<Article> = { | |
// Create Fetch Request | |
let fetchRequest: NSFetchRequest<Article> = Article.fetchRequest() | |
// Configure Fetch Request | |
fetchRequest.sortDescriptors = [NSSortDescriptor(key: #keyPath(Article.sourceName), ascending: true)] | |
// Create Fetched Results Controller | |
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.persistentContainer.viewContext, sectionNameKeyPath: nil/*#keyPath(Article.sourceName)*/, cacheName: nil) | |
// Configure Fetched Results Controller | |
fetchedResultsController.delegate = self | |
return fetchedResultsController | |
}() | |
// Delete all entities | |
let articles = fetchedResultsController.fetchedObjects | |
if let articles = articles { | |
for article in articles { | |
article.managedObjectContext?.delete(article) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment