【SwiftUI로 만드는 macOS 앱】 CoreData 샘플

6366 단어 macosSwiftUI

완성 이미지





Entity





코드



ContentView.swift
import SwiftUI

func getAllStudents() -> NSFetchRequest<Student> {
  let request: NSFetchRequest<Student> = Student.fetchRequest()
  request.sortDescriptors = []
  return request
}

struct ContentView: View {

    @Environment(\.managedObjectContext) var moc

    @FetchRequest(fetchRequest: getAllStudents()) var students: FetchedResults<Student>

    var body: some View {
        VStack {
            Text("Student List")
            List {
                ForEach(students, id: \.id) { student in
                    HStack {
                        Text(student.name ?? "Unknown")
                        Button("delete", action: {
                            self.removeStudent(student: student)
                        })
                    }
                }
            }
            Button("add") {
                let names = ["taro", "yuki", "ken", "bob", "john"]
                let student = Student(context: self.moc)
                student.id = UUID()
                student.name = names.randomElement()
                try? self.moc.save()
            }
        }
    }

    func removeStudent(student: Student) {
        moc.delete(student)
        do {
            try moc.save()
        } catch {
            // handle error
        }
    }
}

좋은 웹페이지 즐겨찾기