CRUD in SwiftUI

First of all, create your demo project then right click project file -> Select Data Model -> give name “SubjectsContainer” and finally tap Create Button.

After create core data file next create Entity. For create entity select Add Entity in buttom side and give it entity name “SubjectEntity“. After create entity then add attributes name which type will be String.

Now create CoreDataViewModel class where we will build all functionality for core data so that user can add, update, retrive, delete data.

//
//  CoreDataViewModel.swift
//  CoreDataSwitUIDemo
//
//  Created by Joynal Abedin on 4/3/23.
//
import SwiftUI
import CoreData

class CoreDataViewModel: ObservableObject {
    
    let container: NSPersistentContainer
    @Published var savedEntities: [SubjectEntity] = []
    
    init() {
        container = NSPersistentContainer(name: "SubjectsContainer")
        container.loadPersistentStores { description, error in
            if let error = error {
                print("error loading core data: \(error)")
            }else{
                print("successfully loaded core data.")
            }
        }
        fetchSubject()
    }
    
    //Retrive Data
    func fetchSubject(){
        let request = NSFetchRequest<SubjectEntity>(entityName: "SubjectEntity")
        do {
            savedEntities = try container.viewContext.fetch(request)
        } catch let error {
            print(error.localizedDescription)
        }
    }
    
    //Add Data
    func addSubject(text: String){
        let newSubject = SubjectEntity(context: container.viewContext)
        newSubject.name = text
        saveData()
    }
    
    //Save Data
    func saveData(){
        do {
            try container.viewContext.save()
            fetchSubject()
        } catch let error {
            print(error.localizedDescription)
        }
    }
    
    //Delete Data
    func deleteSubject(index: IndexSet) {
        guard let index = index.first else {return}
        let entity = savedEntities[index]
        container.viewContext.delete(entity)
        saveData()
    }
    
    //Update Data
    func updateSubject(entity: SubjectEntity) {
        let currentName = entity.name ?? ""
        let newName = currentName + " _updated "
        entity.name = newName
        saveData()
    }
    
}

UI Part

struct ContentView: View {
    
    @StateObject private var vm: CoreDataViewModel = CoreDataViewModel()
    @State private var textFieldText: String = ""
    
    var body: some View {
        NavigationView {
            VStack {
                TextField("Add subject here", text: $textFieldText)
                    .font(.headline)
                    .padding(.leading)
                    .frame(height: 55)
                    .background(.cyan)
                    .cornerRadius(19)
                    .padding(.horizontal)
                
                Button {
                    guard !textFieldText.isEmpty else {return}
                    vm.addSubject(text: "📕" + textFieldText)
                    textFieldText = ""
                } label: {
                    Text("Save")
                        .frame(height: 50)
                        .frame(maxWidth: .infinity)
                        .background(.pink)
                        .cornerRadius(10)
                        .padding(.horizontal)
                        .foregroundColor(.white)
                }
                Spacer()
                List {
                    ForEach(vm.savedEntities) { entity in
                        Text(entity.name ?? "no name")
                            .onTapGesture {
                                vm.updateSubject(entity: entity)
                            }
                    }
                    .onDelete(perform: vm.deleteSubject)
                }
                .listStyle(.plain)
            }
            .navigationTitle("Subject List")
        }
        
    }
}

//MARK: - Preview
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Github Source Code: https://github.com/Joynal279/CoreDataSwitUIDemo

461 thoughts on “CRUD in SwiftUI

Leave a Reply

Your email address will not be published. Required fields are marked *