Search code examples
iosswiftcore-data

Adding data of one entity to other entity Coredata


I have an entity named as Course and other as Tasks. To complete a course, user can create multiple Tasks. Now i have a screen with UITextFields that takes Course data and store it. User can create multiple courses and see them in a tableview.

Now, if the user selects a course, he will get the course detail fetched from the coredata, but at the same time he can also add a task in that course.

So what my issue is : How do i know that the task that is being saved has to be linked to that particular course that the user has selected.

Screenshot of DB Attached: Tasks Coursework

Comment if i am not clear.

This is what i am trying to do in CoreDataHandler.swift file

  class func saveTask(courseWorkName : CourseWork, taskName:String, percentComplete:Int, startDate:Date, endDate: Date, notes: String) -> Bool {
    let context = getContext()
    let entity = NSEntityDescription.entity(forEntityName: "Tasks", in: context)
    let task = NSManagedObject(entity: entity!, insertInto: context)

    let entity1 = NSEntityDescription.entity(forEntityName: "CourseWork", in: context)
    let courseWork = NSManagedObject(entity: entity1!, insertInto: context)


  //  task.setValue(entity1, forKey: "courseworkName")
    task.setValue(taskName, forKey: "taskName")
    task.setValue(percentComplete, forKey: "moduleName")
    task.setValue(notes, forKey: "notes")
    task.setValue(startDate, forKey: "startDate")
    task.setValue(endDate, forKey: "dueDate")
    task.setValue(courseWorkName, forKey: "courseWork")


    do {
        try context.save()
        return true
    }catch {
        return false
    }
}

Solution

  • Pass your courseWork Object to next pushed controller and access it.

    At the time of Entering data into table do it like:

    objCourse.tasks.append(task)
    task.courseWork = objCourse
    

    By doing this you could achieve inverse relationship. Using this you can access course using task and vice versa.

    Access it like:

    objCourseWork.tasks
    objTask.courseWork