访问 SwiftData 模型的关系属性时崩溃

iku*_*hub 11 swift-data

我有两个一对多模型,在尝试访问模型的关系属性时遇到无法解释的崩溃。

错误原因如下:

线程 1:EXC_BREAKPOINT(代码=1,子代码=0x1038f4448)

Xcode 显示错误发生在模型的 .getValue(for: .rows) 方法中。 在此输入图像描述

这是我的 SwiftData 模型:

@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
    }
}

Run Code Online (Sandbox Code Playgroud)

这是我的代码:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我访问模型的关系属性,程序就会崩溃。比如传递给一个变量。

var myRows = section.rows
Run Code Online (Sandbox Code Playgroud)

或者只打印模型的关系属性也会崩溃

print(section.rows)
Run Code Online (Sandbox Code Playgroud)

Xcode15 测试版 5。

Joa*_*son 5

SwiftData beta 中的另一个错误。即使在某些情况下访问关系属性时发生崩溃,它也与值的分配有关。解决方法是交换分配

let row = Row()
let section = Section()
row.section = section
Run Code Online (Sandbox Code Playgroud)

我还更改了 init,因为Section在 init 中传递和设置关系属性似乎是另一个问题。

请注意,您的代码中存在一个错误,您将row对象两次分配给该部分。

  • @maximkrouk也许[这个答案](/sf/answers/5425021731/)可能会有所帮助。 (2认同)