import Foundation
import CoreData
class PersistenceManager {
static let shared = PersistenceManager()
let container: NSPersistentContainer
// MARK: - 初期化
init(){
container = NSPersistentContainer(name: "Database") // name: モデルファイルの名前
// Persistent Store を読み込む
container.loadPersistentStores { description, error in
if let error = error {
print("Error loading stores: \(error)")
}
else {
print("Successfully loaded stores")
}
}
}
// MARK: - CRUD操作
// CREATE
func addTask(text:String){
let newTask = Task(context: container.viewContext)
newTask.name = text
// データベースに変更内容を保存する
save()
}
// READ
func fetchTasks() -> [Task]{
let request = NSFetchRequest<Task>(entityName: "Task")
do {
let allTasks = try container.viewContext.fetch(request)
return allTasks
} catch {
print("Error fetching data: \(error)")
}
return []
}
// DELETE
func deleteTask(task:Task){
container.viewContext.delete(task)
// データベースに変更内容を保存する
save()
}
// COMMIT TO DATABASE
private func save(){
do {
// ContainerのViewContextでの変更をデータベースに保存
try container.viewContext.save()
} catch {
print("Error saving to database: \(error)")
}
}
}
目次
ViewModelから呼び出す
import Foundation
class MainViewModel: ObservableObject {
@Published var allTasks:[Task] = []
@Published var inputText:String = ""
// データの読み込み
func loadLatestTasks(){
allTasks = PersistenceManager.shared.fetchTasks()
}
// データの追加
func addTask (){
if(inputText != ""){
PersistenceManager.shared.addTask(text: inputText)
}
}
// データの削除
func deleteTasks(indexSet: IndexSet){
for index in indexSet {
// Delete from database
let goalToDelete = allGoals[index]
PersistenceManager.shared.deleteGoal(goal: goalToDelete)
// Delete it from allGoals
allGoals.remove(at: index)
}
}
}
Comment