Skip to content

Instantly share code, notes, and snippets.

@KingNexu
Last active December 6, 2021 06:44
Show Gist options
  • Save KingNexu/c09b56d9c73af3396a2d7415c2890f40 to your computer and use it in GitHub Desktop.
Save KingNexu/c09b56d9c73af3396a2d7415c2890f40 to your computer and use it in GitHub Desktop.
[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
persistentContainer.viewContext.delete(movie)
//Delete through saving
do {
try persistent.Container.viewContext.save()
} catch {
persistent.Container.viewContext.rollback()
print("Failed to save context \(error.localizedDescription)")
}
}
func getReviewsByMovie(vm: MovieViewModel) {
let movie = CoreDataManager.shared.getMovieById(id: vm.id)
if let movie = movie {
DispatchQueue.main.async{
///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 self.reviews
self.reviews = (movie.reviews?.allObjects 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