UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Connecting two entities doesn't always work

Forums > Swift

I have an app with multiple coreData entities. The user can connect them. For example: a company can be connected to a employee.

But previously i only got the connecting to work on the detail view, not on the add view. Because the entitie has to be created first. I thought that i found a way to get this to work. But the problem is that it works sometime and not always.

This is the function that creates an entity:

    func addJob(rating: Int16, jobTitle: String, jobListing: String, location: String) {
        let newJob = JobEntity(context: manager.context)
        newJob.jobTitle = jobTitle
        newJob.jobListing = jobListing
        newJob.location = location

        save()
        setJobCounter()
        EntityConnector.instance.addNewJobToCompany(companyIndex: companyIndex, vm: CoreDataViewModel())
    }

The last line calls a function that connects the entities. This is the class:

import Foundation

class EntityConnector {

    static let instance = EntityConnector()

    func addNewJobToCompany(companyIndex: Int, vm: CoreDataViewModel) {
        let jobIndex = vm.getJobCount() - 1
        let currentCompany = vm.companies[companyIndex]

        currentCompany.addToJobs(vm.jobs[jobIndex])
        vm.save()
    }

    func addContactToCompany(companyIndex: Int, vm: CoreDataViewModel) {
        let contactIndex = vm.getContactCount() - 1
        let currentCompany = vm.companies[companyIndex]

        currentCompany.addToContacts(vm.contacts[contactIndex])
        vm.save()
    }
}

Does anyone have any idea how to solve this?

2      

In your first code example. Where does the companyIndex come from? But nevertheless, when there is a 1:m relationship in your CoreData model between Company and Job you should be able to assign the Company to the Job with newJob.company = company or how your relationship is named in your model. Usually, there is no need for an extra EntityConnector.

If it's a many to many relationship there should be a method on Job name d addToCompanies (or something like that).

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.