Yatendra
Yatendra

Reputation: 1306

How to pass object to other view in SwiftUI with core data

I am trying to just simple CURD operations with core data in SwiftUI. I have already googling but didn't get succees.

I have successfully implemented Create operation. Now I am trying to implement the "Edit" operation. for edit operation, I want to pass an object to second view.

What I am trying:

//ContentView

struct ContentView: View {
    
    @Environment(\.managedObjectContext) var managedObjectContext
    
    @FetchRequest(entity: StudentCoreData.entity(),sortDescriptors: [])
   
    var students: FetchedResults<StudentCoreData>
    @State var showAddStudentSheet = false

    var body: some View {
        
         NavigationView{
            VStack
                {
                    List {
                        ForEach(self.students, id: \.id) { student in
                            NavigationLink(destination: AddStudent())
                            {
                                Text(student.name ?? "Unknown")
                            }
                        }
                    }
            }
            .navigationBarTitle("students")
            .navigationBarItems(trailing: Button(action: {
                //  self.showAddStudentSheet = true
                self.showAddStudentSheet.toggle()
            }, label: {
                Text("Add")
            }))
                .sheet(isPresented: $showAddStudentSheet) {
                    AddStudent().environment(\.managedObjectContext, self.managedObjectContext)
            }
            
        }
    }
}

 
struct ContentView_Previews: PreviewProvider {
    
    static var previews: some View {
        
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        
        return ContentView().environment(\.managedObjectContext, context)
    }
}


//And AddStudent View
struct AddStudent : View {
    
    @Environment(\.managedObjectContext) var managedObjectContext
    @Environment (\.presentationMode) var presentationMode
    
    @State var studentName = ""

    var body: some View
    {
        
        NavigationView
            {
                Form
                    {
                        
                        Section(content: {
                            
                            Text("Student Details")
                                .font(.headline)
                                .fontWeight(.medium)
                                .multilineTextAlignment(.leading)
                                .padding(.leading, 5.0)
                            TextField("Name", text: $studentName)
                                .padding(.all, 16.0)
                            
                        })
                        
                        
                        Section(content: {
                            Button(action: {
                                guard self.studentName != "" else {return}
                                let newOrder = StudentCoreData(context: self.managedObjectContext)
                                newOrder.name = self.studentName
                                newOrder.id = UUID()
                                do {
                                    try self.managedObjectContext.save()
                                    print("Order saved.")
                                    self.presentationMode.wrappedValue.dismiss()
                                } catch {
                                    print(error.localizedDescription)
                                }
                                
                            }) {
                                Text("Click me")
                                    .font(.system(size: 18))
                                    .multilineTextAlignment(.center)
                            }
                            .frame(minWidth: 0, maxWidth: .infinity, alignment: .center)
                            
                        })
                }
                .navigationBarTitle("Add Student")
                .navigationBarItems(leading:  Button(action: {
                    self.presentationMode.wrappedValue.dismiss()

                }, label: {
                    Text("Cancel")
                }))
        }
        
        
    }
}

struct AddStudent_Previews: PreviewProvider {
    static var previews: some View {
        AddStudent()
    }
}

I want to pass student object on click row of the table list.

I want to know how to pass the variable. How to make this variable on "Add student" view, because if I make a new variable it reflects at all places where AddStudent class called, and then new problems come.

Please help.

Upvotes: 4

Views: 2877

Answers (2)

Carlos Maria Caraccia
Carlos Maria Caraccia

Reputation: 500

You could pass it using an @StateObject

   struct AddStudent : View {

      @StateObject var student:Student

    init(student:Student) {
    _student = StateObject(wrappedValue:student)
    
    }

..... continue with your struct

In the navigation link your selected student

 NavigationLink(destination: AddStudent(student:Student))

Upvotes: 2

nurnachman
nurnachman

Reputation: 4565

Fetch the corresponding object from the table-list, and inject it to a custom edit view

let selectedObject = //...fetch from coredata or from a cached dataset... editView.objectToEdit = selectedObject

Upvotes: 0

Related Questions