ikunhub
ikunhub

Reputation: 283

Crash when accessing relationship property of SwiftData model

I have two one-to-many models and I'm getting an unexplained crash when trying to access the relationship properties of the models.

The reason for the error is as follows:

Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1038f4448)

Xcode shows that the error occurs in the model's .getValue(for: .rows) method. enter image description here

This is my SwiftData model:

@Model class Row {
    var section: Section?
    
    init(section: Section? = nil) {
        self.section = section
    }
    init() {
        self.section = nil
    }
}

@Model class Section {
    @Relationship(.cascade, inverse: \Row.section)
    var rows: [Row] = []
        
    init(rows: [Row]) {
        self.rows = rows
    }
}

This is my code:

class ViewController: UIViewController {
    var container: ModelContainer?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        do {
            container = try ModelContainer(for: [Section.self, Row.self])
        } catch {
            print(error)
        }
              
        let row = Row()
        let section = Section(rows: [row])
        
        var myRows = section.rows    //Accessing relationship properties causes crash
        
        print("hello")  //no print
    }
}

If I access the relationship property of the model, the program crashes. Such as passing to a variable.

var myRows = section.rows

Or just printing the relationship property of the model also crashes

print(section.rows)

Xcode15 beta 5.

Upvotes: 17

Views: 2196

Answers (3)

palme
palme

Reputation: 2609

This is already answered, however I came across the same error after I added a relationship to my model. It seems obvious now but I just had to delete my app and reinstall it. This way the new data structure was taken in the app and the crash disappeared (probably also would have worked with a merging strategy).

I also needed to insert the model into the ModelContext.

Upvotes: 0

mandalorianMac
mandalorianMac

Reputation: 21

You need to tell SwiftData that you're using a delete rule like this: @Relationship(deleteRule: .cascade) var notes: [Note]

Upvotes: 1

Joakim Danielson
Joakim Danielson

Reputation: 51831

Another bug in the SwiftData beta. It is related to the assignment of values even if in some circumstances the crash occurs when accessing the relationship propert. A workaround is to swap the assignment

let row = Row()
let section = Section()
row.section = section

I also changed the init so it for Section since passing and setting a relationship property in an init seems to be another issue.

Note that there was a bug in your code where you assigned the row object twice to the section.

Upvotes: 8

Related Questions