[Core Data] Save, Get, Delete, Update

brick·2022년 12월 15일
0

Core Data

목록 보기
1/2
post-thumbnail
class CoreDataManager {
    
    let persistentContainer: NSPersistentContainer
    
    init() {
        persistentContainer = NSPersistentContainer(name: "HelloCoreDataModel")  // (.xcdatamodel)파일 이름
        persistentContainer.loadPersistentStores { description, error in
            if let error = error {
                fatalError("Core Data Store failed to initialize \(error.localizedDescription)")
            }
        }
    }
    
    func updateMovie() {
        
        do {
            try persistentContainer.viewContext.save()
        } catch {
            persistentContainer.viewContext.rollback()
        }
    }
    
    func deleteMovie(movie: Movie) {
        
        persistentContainer.viewContext.delete(movie)
        
        do {
            try persistentContainer.viewContext.save()
        } catch {
            persistentContainer.viewContext.rollback()
            print("Failed to save contetx \(error.localizedDescription)")
        }
    }
    
    func getAllMovies() -> [Movie] {
        
        let fetchRequest: NSFetchRequest<Movie> = Movie.fetchRequest()
        
        do {
            return try persistentContainer.viewContext.fetch(fetchRequest)
        } catch {
            return []
        }
    }
    
    func saveMovie(title: String) {
        
        let movie = Movie(context: persistentContainer.viewContext)
        movie.title = title
        
        do {
            try persistentContainer.viewContext.save()
            print("Movie saved!")
        } catch {
            print("Failed to save movie \(error)")
        }
    }
}

1개의 댓글

comment-user-thumbnail
2024년 2월 17일

As the sun dipped below the horizon, casting a warm glow across the sky, I found myself craving a bit of cinematic magic to unwind after a long day. With https://kinogoby.com/ a bowl of buttery popcorn in hand, I settled onto the couch and began to browse the site's extensive collection of films. After much deliberation, I decided to revisit an old favorite—a classic comedy that never failed to bring a smile to my face

답글 달기