SwiftData stores object without insert

418 Views Asked by At

When I instantiate a model and set a relationship to a persistent object, the model is stored in the container without calling insert on it.

Given

@Model
final class Order {
    @Attribute(.unique)
    var orderId: String
    
    var items: [Item] = []
    
    init(orderId: String) {
        self.orderId = orderId
    }
}

@Model
final class Item {
    @Attribute(.unique)
    var timestamp: Date
    
    var order: Order?
    
    init(timestamp: Date) {
        self.timestamp = timestamp
    }
}

I create a Item

let item = Item(timestamp: Date())
// here the order is not stored
item.order = sharedModelContainer.mainContext.anOrder
// here after setting the relationship to an existing order the item is stored

anOrder is just

extension ModelContext {
    var anOrder: Order? {
        let desc = FetchDescriptor(predicate: #Predicate<Order> { order in true })
        let orders = try! fetch(desc)
        return orders.first
    }
}

No insert is called on any context.

Disabling auto-save is not a solution. My question is why it is saved without inserting it.

Is it supposed to be like that? Is it desirable?

0

There are 0 best solutions below