在尝试加载模型数据时,SwiftData触发了EXC_BREAKPOINT
我在单元测试中尝试用SwiftData加载模型数据时,遇到了一个运行时“错误”,难以解决。
我在MainActor上使用makeModelContext函数来创建一个内存中的模型上下文:
/// Create an in-memory ModelContext containing all app models for testing.
/// This mirrors the models registered in the App's ModelContainer.
@MainActor static func makeModelContext() throws -> ModelContext {
// Use an in-memory model configuration for tests to avoid CloudKit/SwiftData background
// registration collisions with the app's shared ModelContainer.
let config = ModelConfiguration(isStoredInMemoryOnly: true)
let schema = Schema([
Car.self,
Charger.self,
ChargingCostPlan.self,
ChargingSession.self,
ChargingSessionTemplate.self,
PriceElement.self,
Location.self,
HomeConsumption.self
])
let container = try ModelContainer(for: schema, configurations: [config])
// Disable autosave to avoid background persistence during tests
container.mainContext.autosaveEnabled = false
return container.mainContext
}
在我的测试函数中,我也在MainActor中调用makeModelContext函数:
@Test("Import a representative subset of the backup JSON")
@MainActor
func testImportRepresentativeSubset() async throws {
// Locate the test data JSON next to this test file
let testFileURL = URL(fileURLWithPath: #file).deletingLastPathComponent().appendingPathComponent("TestData_2026-03-07.json")
let raw = try Data(contentsOf: testFileURL)
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let backup = try decoder.decode(DataEncoder.Backup.self, from: raw)
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
encoder.dateEncodingStrategy = .iso8601
let data = try encoder.encode(backup)
// Create an in-memory ModelContext (helper provided by test infra)
let modelContext = try TestHelpers.makeModelContext()
modelContext.autosaveEnabled = false
// Import
let report = try DataImporter.importFrom(data: data, into: modelContext)
...
在上述代码的最后一行,我把测试函数中的这个modelContext传递给待测试的函数:
/// Import from raw JSON Data (the shape produced by `DataEncoder.Backup`).
/// - Parameters:
/// - data: JSON data produced by `DataEncoder.export`
/// - modelContext: the SwiftData `ModelContext` to insert objects into
/// - Returns: an import report summarising the operation.
@MainActor
public static func importFrom(data: Data, into modelContext: ModelContext) throws -> DataImportReport {
var report = DataImportReport()
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
do {
let backup = try decoder.decode(DataEncoder.Backup.self, from: data)
// Prefetch existing objects once to avoid repeated fetches and actor issues
let existingCars: [Car] = (try? modelContext.fetch(FetchDescriptor<Car>())) ?? []
...
在上述代码的最后一行,我收到了以下运行时信息,测试过程因此停止:
Task 55: EXC_BREAKPOINT (code=1, subcode=0x1d9d2a8b4)
我尝试通过网络搜索、Github Copilot和 Xcode Coding Assistant来寻求解决方案,但没有一个建议有帮助。我检查了以下几点:
- 模型注册已完成
- modelContext有效
- 谓词有效
有什么建议,可能的根本原因是什么?
解决方案
问题在于内存中的modelContext的容器被释放了。这篇帖子给出了一个解决方案:
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。