Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
[CoreData] #CoreData #SwiftUI #iOS
import Foundation
import CoreData
final calss CoreDataManger {
let persistentContainer: NSPersistentContainer
init() {
///To Initialize persistent container you have to pass in the file name of the model
persistentContainer = NSPersistentContainer(name: "HelloCoreDataModel")
///Persistent Container has the Fields description and error
persistentContainer.loadPersistentStores{ (description, error) in
///Error Handling
if let error = error{
fatalError("Core Data Store failed to initialize \(error.localizedDescription)")
//Functions you need to manage Data like Delete Save etc.
func deleteMovie(movie: Movie) {
//Mark for deletion
//Delete through saving
do {
} catch {
print("Failed to save context \(error.localizedDescription)")
func getReviewsByMovie(vm: MovieViewModel) {
let movie = CoreDataManager.shared.getMovieById(id:
if let movie = movie {
///Get all Reviews and cast it into an array
///Map over it to make an instance of review for every element in the array
///assign it to = ( as! [Review]).map(ReviewViewModel.init)
func getAllMovies() -> [Movie] {
//You can pass in the type you wan't to have in <TYPE> | The Movie class has already a fetch request we can pass in
let fetchRequest: NSFetchRequest<Movie> = Movie.fetchRequest()
//Returns the Fetched data with error handling
do {
return try persistentContainer.viewContext.fetch(fetchRequest)
} catch{
return []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment