ios – How to Delete Objects in an Array without Using modelContext in SwiftUI/SwiftData?


Let’s say in SwiftUI / SwiftData, we have two models:

@Model
final class Thing1 {
    
    private var things:[Thing2]
    
    func deleteThing(thing: Thing2) {
        things.removeAll(where: {$0.persistentModelID == thing.persistentModelID})
    }
    
    init(things: [Thing2]) {
        self.things = things
    }
    
}

@Model
final class Thing2 {

    init() {}
    
}

The problem here is that, when we use the delete function, as we know, it’s not really deleted in SwiftData.

Normally we would use the modelContext to do that, but… for lengthy reasons (see this question), I’m experimenting with not doing it that way. I’m also assuming that we can’t get a working reference to the modelContext from inside Thing1.

I know that it is possible to implicitly delete items without using modelContext. For example using @Relationship(deleteRule: .cascade), but this is only for single items, not arrays.

Is there some way to do this?

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img