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)")
}
}
}
[Core Data] Save, Get, Delete, Update
bromp • 2022년 12월 15일 PM 06:45 • 86 • 0
댓글
첫 번째 댓글을 남겨보세요 :)