CoreValue icon indicating copy to clipboard operation
CoreValue copied to clipboard

Inverse Relationships

Open tkohout opened this issue 9 years ago • 4 comments

Hi, I started using modified version of CoreValue on one of my projects and one problem with CoreValue became imminent.

let employee = Employee(objectID: nil, name: "John Doe", age: 18, position: "Clerk", department: "Carpet", job: "Cleaner", shop:nil)
var shop = Shop(objectID: nil, name: "Carpet shop", employees: [employee])

try! shop.save(context)
//Will crash in infinite loop
let shops:[Shop] = Shop.query(context, predicate: nil)

The Employee have inverse relationship with Shop. When I add employee to the Shop entity and save the corevalue will populate the inverse relationship. When I try to query the Shop program will crash in infinite loop.

This is of course logical, because we are working with structs, but it gets quite limiting. The solution is to not to unbox the inverse relationship but I found out that sometimes I need to use both sides of relationship.

I wonder if you are aware of the problem and if you have and idea how to solve it

Thanks

tkohout avatar Mar 01 '16 11:03 tkohout

Hey, actually I think that this should work fine already. I may be misunderstanding you though. I've added a new unit test to the current master. Could you see if that works for you?

The test in question is in CoreValueTests.swift:

    func testInfiniteLoop() {
        let employee = StoredShopEmployee(objectID: nil, name: "John Doe", age: 18, position: "Clerk", department: "Carpet", job: "Cleaner", shop:nil)
        var shop = StoredEmployeeShop(objectID: nil, name: "Carpet shop", employees: [employee])

        try! shop.save(context)
        //Will crash in infinite loop
        let shops:[StoredEmployeeShop] = try! StoredEmployeeShop.query(context, predicate: nil)
        print(shops)
        XCTAssertNotNil(shops)
    }

terhechte avatar Mar 09 '16 01:03 terhechte

It doesn't crash because you have two relationships between Employee and Shop (in core data) - shop and work.

The core data is confused and populates the other relationship which you don't unbox in the StoredEmployee entity.

Change it and you should see the crash.

tkohout avatar Mar 10 '16 18:03 tkohout

Is there any development in this case? Because I'm interested how do inverse relationships work and if they do.

alistra avatar Nov 25 '16 11:11 alistra

I've tried many way to deal with inverse method, and try to find in the sample. But still can not find an appropriate way to deal with it. For example, I can not try to save employee with a shop, which cause a big inconvenience.

var shop = Shop(objectID: nil, name: "Carpet shop", employees: nil) let employee = Employee(objectID: nil, name: "John Doe", age: 18, position: "Clerk", department: "Carpet", job: "Cleaner", shop: shop) //inverse usage here, but failed with some reason..

try! employee.save(context)

LazyTravis avatar Nov 22 '17 16:11 LazyTravis