Search code examples
swiftdata

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.


Solution

  • 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.